Continue learning
Practice related DSA questions in the same topic.
Choose nonadjacent entries of nonnegative value to maximize the total. Return the best sum.
Choose nonadjacent entries of nonnegative value to maximize the total. Return the best sum.
def solve(values, target): twoBack = 0 best = 0 i = 0 while (i < len(values)): nextBest = max(best, (twoBack + values[i])) twoBack = best best = nextBest i = (i + 1) return bestCompare skipping this position with taking it.
Compare skipping this position with taking it.
Pick paid workshops on nonconsecutive days and compare attending today with keeping yesterday’s schedule.
Compare skipping today with taking today plus the best available two positions back.
O(n) time · O(1) auxiliary space
Worked example · {"values":[4,1,2,7,5],"target":0} ⇒ 11
Edge case 1 · {"values":[],"target":0} ⇒ 0
Edge case 2 · {"values":[3],"target":0} ⇒ 3
Taking every locally larger value can block a better pair later.
How would a circular street change the first and last choices?