fork download
  1. /**
  2.  * 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.
  3.  */
  4. object Main extends App {
  5. val inputArray = Array(5, 15, 10, 40, 50, 35)
  6. print(getMaxAlternativeElementSum(0, 0, inputArray(0)))
  7. def getMaxAlternativeElementSum(tracker: Int, prevSum: Int, curSum: Int):Int = tracker match {
  8. case _ if tracker == 0 => getMaxAlternativeElementSum(tracker+1, 0, inputArray(tracker))
  9. case _ if tracker >= inputArray.length => curSum
  10. case _ => val maxSum = curSum.max(prevSum)
  11. getMaxAlternativeElementSum(tracker+1, maxSum, prevSum+inputArray(tracker))
  12. }
  13. }
Success #stdin #stdout 0.39s 382016KB
stdin
Standard input is empty
stdout
90