fork download
  1. def max_sum(arr)
  2. return (arr+[0]).max if arr.size < 3
  3.  
  4. i=2
  5. curr_max = []
  6. curr_max[0] = (arr[0..0]+[0]).max
  7. curr_max[1] = (arr[0..1]+[0]).max
  8.  
  9. while i<arr.size
  10. curr_max[i] = [arr[i] + curr_max[i-2], curr_max[i-1]].max
  11. i+=1
  12. end
  13. curr_max.last
  14. end
  15.  
  16. puts max_sum([])
  17. puts max_sum([-1, -2])
  18. puts max_sum([5, 1, 1, 5])
  19. puts max_sum([2, 0, 4, -2, -3, 0, 6, 2, 5])
  20. puts max_sum([-1, -1, 2, 0, 4, -2, -3, 0, 6, 2, 5])
  21. puts max_sum([0, 3, 4, 3, 0])
Success #stdin #stdout 0s 28216KB
stdin
Standard input is empty
stdout
0
0
10
17
17
6