Inspired by this (off topic) post
Given an array of numbers, find the largest sum over a subarray not containing two adjacent elements
[1,2,3,4] -> 6 // [_,2,_,4]
[1,2,3,4,5] -> 9 // [1,_,3,_,5]
[2,2,1,1,2,1,1,2] -> 7 // [2,_,1,_,2,_,_,2]
[3,1,4,1,5,9,2] -> 16 // [3,_,4,_,_,9,_]
[9,8,7,9,9,8] -> 26 // [9,_,_,9,_,8]
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1] -> 21
Rules
- You can assume that all number in the array are positive integers
- This is code-golf the shortest solution wins
Optional additional requirement:
- Your solution has to run in polynomial time (\$O(n^k)\$ for some integer k)
sum[..., _, x]
), and one where it was omitted (sum[..., _]
). See O B's answer. \$\endgroup\$