Given an array of non-negative numbers, find the maximum sum you can take without choosing two adjacent elements (e.g. [2,7,9,3,1] -> 12 = 2+9+1).
At each element you either skip it (keep the best-so-far) or take it plus the best from two positions back: curr = max(prev, prevPrev + x). Track just two rolling values for O(n) time, O(1) space. Greedily taking the largest values can violate the adjacency rule.
public static int rob(int[] a) {
int prev = 0, curr = 0;
for (int x : a) {
int temp = Math.max(curr, prev + x);
prev = curr;
curr = temp;
}
return curr;
}function rob(a) {
let prev = 0, curr = 0;
for (const x of a) {
const temp = Math.max(curr, prev + x);
prev = curr;
curr = temp;
}
return curr;
}def rob(a):
prev = curr = 0
for x in a:
prev, curr = curr, max(curr, prev + x)
return currThe take-or-skip recurrence models scheduling with cooldowns and selecting non-conflicting intervals for maximum value.
A candidate greedily sums the largest non-adjacent-looking values and fails on [2,1,1,2] (returns 3 instead of 4). Why is DP needed?