wavec022

memoization

Feb 12th, 2021 (edited)
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.70 KB | None | 0 0
  1. def maxSum(arr: Array[Int]): Int = {
  2. def maxFrom(index: Int): Int = {
  3. if(index >= arr.length) return 0
  4. else arr(index) + (maxFrom(index+2) max maxFrom(index+3))
  5. }
  6. maxFrom(0) max maxFrom(1)
  7. }
  8.  
  9. ===========
  10.  
  11. Memoization -- remembering answers that you've already seen
  12.  
  13. We can actually use a special data structure here; map where keys are consecutive integers starting with zero == an array
  14.  
  15. def maxSum(arr: Array[Int]): Int = {
  16. var memo = Array.fill(arr.length+2)(-99)
  17. def best(index: Int): Int = {
  18. if(memo(i) == -99) {
  19. memo(i) == {
  20. if(index >= arr.length) return 0
  21. else (a(i) + best(i+2)) max best(i+1)
  22. }
  23. }
  24. memo(i)
  25. }
  26. best(0)
  27. }
Add Comment
Please, Sign In to add comment