wavec022

dynamic programming

Feb 19th, 2021 (edited)
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.75 KB | None | 0 0
  1. def maxSumNoAdjacent(a: Array[Int]): Int = {
  2. def best(i: Int): Int = {
  3. if(i >= a.length) 0
  4. else (a(i) + best(i+2)) max best(i+1)
  5. }
  6. best(0)
  7.  
  8. /////
  9. val best = Array.fill(a.length+2)(-99)
  10. for(i <- best.indices.reverse) {
  11. best(i) = {
  12. if(i >= a.length) 0
  13. else (a(i) + best(i+2)) max best(i+1)
  14. }
  15. }
  16. best(0)
  17. }
  18.  
  19. =====
  20.  
  21. def lis(a: Array[Int]): Int = {
  22. // best(i) is the length of the lis that actively starts at index i
  23. // def best(i: Int): Int = {
  24. val best = Array.fill(a.length)(-99)
  25. for(i <- a.indices.reverse) {
  26. best(i) = {
  27. if( (i+1 to a.length).forall(j => a(j) <= a(i)) ) 1
  28. else 1 + (i+1 to a.length).filter(j => a(j) > a(i)).map(best(_)).max
  29. }
  30. }
  31. //best(i)
  32. best.max
  33. }
Add Comment
Please, Sign In to add comment