【发布时间】:2014-03-25 17:24:12
【问题描述】:
我正在尝试解决计算数组的最大子序列总和的问题,其中没有相邻元素是该总和的一部分。 对于第 i 个索引处的每个元素,我检查 i-2 和 i-3 个元素的最大值,并将第 i 个元素添加到其中以获得最大值,这样两个相邻元素不包含在任何总和中。
我在 Scala 中以递归方式解决了它: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))
}
}
每次,我使用递归方法将前两个总和带到下一次迭代。我可以使用任何 Scala 习语优雅地做到这一点吗?
【问题讨论】: