🔗 View the original problem on LeetCode
We have to decide for every house whether to rob it or skip it.
Robbing house i means we cannot rob house i-1,
so we look two steps back; skipping it means we keep whatever we had
until the previous house. Dynamic programming with only two rolling
variables (rob1, rob2) is enough.
They act like a sliding window of size 2 over the DP table.
function rob(nums) {
let rob1 = 0; // best up to i-2
let rob2 = 0; // best up to i-1
for (const num of nums) {
const temp = Math.max(num + rob1, // rob current
rob2); // skip current
rob1 = rob2; // shift window forward
rob2 = temp;
}
return rob2;
}
Trace the array: [5, 1, 2, 10, 6, 2, 7, 9, 3, 1]
Decision Logic:
Click “Next Step” to begin!