scalaz - Max subsequence sum in the array with no two adjacent elements in Scala -


i trying solve problem of calculating max subsequence sum of array no adjacent elements part of sum. every element @ ith index, checking max of i-2 , i-3 elements , adding ith element max 2 adjacent elements not included in sum.

i solved in scala below recursive way : ideone link

/**  * question: given array of positive numbers, find maximum sum of subsequence constraint no 2 numbers in sequence should adjacent in array.   */ object main extends app {   val inputarray = array(5, 15, 10, 40, 50, 35)   print(getmaxalternativeelementsum(0, 0, inputarray(0)))   def getmaxalternativeelementsum(tracker: int, prevsum: int, cursum: int):int = tracker match {     case _ if tracker == 0  => getmaxalternativeelementsum(tracker+1, 0, inputarray(tracker))     case _ if tracker >= inputarray.length => cursum         case _ => val maxsum = cursum.max(prevsum)                            getmaxalternativeelementsum(tracker+1, maxsum, prevsum+inputarray(tracker))   } } 

every time, carrying previous 2 sums next iteration using recursive approach. can elegantly using scala idioms?

not sure if understood correctly want maybe work you:

  def getmaxalternativeelementsum(input: array[int]) : int = {     val sums =       input.zipwithindex.fold((0, 0)) { (acc, elem) =>         elem._2 % 2 match {           case 0 => (acc._1 + elem._1, acc._2)           case 1 => (acc._1, acc._2 + elem._1)         }       }      if (sums._1 > sums._2) sums._1 else sums._2   }  

Comments

Popular posts from this blog

user interface - How to replace the Python logo in a Tkinter-based Python GUI app? -

objective c - Greedy NSProgressIndicator Allocation -

how to set an OCR language in Google Drive -