0

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?

Rajeev
  • 4,762
  • 8
  • 41
  • 63

1 Answers1

1

Not sure if I understood correctly what you want to do but maybe this will work for 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
  } 
atretkow
  • 362
  • 2
  • 8