- Home
- /
- Tutorials
- /
- DSA Tutorial
- /
- 1D Dynamic Programming
Dynamic Programming
1D Dynamic Programming
1D DP means one array of state, where each entry is the best answer up to that index. If the answer at position i depends only on earlier positions, this is the shape.
House robber - non-adjacent choices
You cannot take two adjacent items. At each position: skip it and keep the previous best, or take it and add the best from two positions back.
House robber
javascript
function rob(nums) {
let twoBack = 0 // best excluding the previous item
let oneBack = 0 // best including everything up to the previous
for (const n of nums) {
const take = twoBack + n
const skip = oneBack
;[twoBack, oneBack] = [oneBack, Math.max(take, skip)]
}
return oneBack
}
console.log(rob([2, 7, 9, 3, 1])) // 12 (2 + 9 + 1)