Advertisement
Calabir

Max non-consecutive sum

Jan 28th, 2021
1,132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.16 KB | None | 0 0
  1. import org.junit.Assert.assertEquals
  2.  
  3. import scala.annotation.tailrec
  4.  
  5. /**
  6.  * This problem was asked by Airbnb.
  7.  *
  8.  * Given a list of integers, write a function that returns the largest sum of non-adjacent numbers. Numbers can be 0 or negative.
  9.  *
  10.  * For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5. [5, 1, 1, 5] should return 10, since we pick 5 and 5.
  11.  *
  12.  * Follow-up: Can you do this in O(N) time and constant space?
  13.  * */
  14.  
  15.  
  16. def newAccValue(acc: Array[Int], listValue: Int): Int = {
  17.   if (acc.isEmpty) listValue
  18.   else if (acc.length == 1) math.max(acc(0), listValue)
  19.   else math.max(acc(acc.length - 2) + listValue, acc(acc.length - 1))
  20. }
  21.  
  22. @tailrec
  23. def myFindMaxSum(inList: List[Int], acc: Array[Int]): Int = {
  24.   inList match {
  25.     case List() => acc.last
  26.     case xs :: ys =>
  27.       myFindMaxSum(ys, acc :+ newAccValue(acc, xs))
  28.   }
  29. }
  30.  
  31. val inList1 = List(2, 4, 6, 2, 5)
  32. val inList2 = List(5, 1, 1, 5)
  33. val inList3 = List(5, -1, -1, 5)
  34.  
  35. val emptyArray = Array[Int]()
  36.  
  37. assertEquals(13, myFindMaxSum(inList1, emptyArray))
  38. assertEquals(10, myFindMaxSum(inList2, emptyArray))
  39. assertEquals(10, myFindMaxSum(inList3, emptyArray))
  40.  
  41.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement