【问题标题】:Max subsequence sum in the array with no two adjacent elements in ScalaScala中没有两个相邻元素的数组中的最大子序列和
【发布时间】: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 习语优雅地做到这一点吗?

【问题讨论】:

    标签: scala scalaz


    【解决方案1】:

    不确定我是否正确理解了您想要做什么,但也许这对您有用:

      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
      } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-27
      • 2017-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多