I am trying to solve a problem of calculating max subsequence sum of an array with no adjacent elements are part of that sum. For every element at ith index, i am checking max of i-2 and i-3 elements and adding ith element to that to get max so that two adjacent elements are not included in any sum.
I solved it in Scala below recursive way : ideone link
/**
* Question: Given an array of positive numbers, find the maximum sum of a subsequence with the constraint that no 2 numbers in the sequence should be adjacent in the 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, i am carrying previous two sums to next iteration using recursive approach. Can i do this elegantly using any Scala idioms?