House-robber skip-or-take
Updated
At i: skip a[i] and keep dp[i-1], or take a[i] and keep dp[i-2]. Adjacent houses cannot both be taken. dp[i] = max(dp[i-1], dp[i-2]+a[i]).
What to focus on
Base dp[0]=a[0]; n=2 is max(a[0], a[1]). Taking every max cell without the skip rule double-counts neighbors.
Worked examples
take 4 and 9
a = [4, 1, 9]- dp[0]=4
- dp[1]=max(4, 1)=4
- dp[2]=max(4, 4+9)=13
Result: 13
skip the middle
a = [4, 1, 9]- take 9 forces skip 1
- 4 is not adjacent to 9
- houses 0 and 2
Result: 13
single house
a = [4]- only take 4
Result: 4
Try it
Write robber(a). a is an array of positive integers. dp[i] is max loot on prefix 0..i with no two adjacent. Skip or take at each i. Return dp[n-1]. [4, 1, 9] → 13. [4] → 4.
a is a non-empty array of positive integers. n ≥ 1. Adjacent houses cannot both be taken when n ≥ 2.