A row of houses stands along a street, and nums[i] is how much money is inside house i. You may take the money from any houses you like, with one rule: you may never take from two houses that stand next to each other.
Return the largest total you can collect.
Example 1
Input: nums = [3, 1, 4, 9, 2] Output: 12 Why: houses 0 and 3: 3 + 9
2 more examples and the constraints
Example 2
Input: nums = [5, 1, 1, 5] Output: 10 Why: houses 0 and 3; skipping two houses in a row is fine
Example 3
Input: nums = [7] Output: 7 Why: a single house is always safe
Constraints
- 1 ≤ number of houses ≤ 100
- 0 ≤ money in a house ≤ 400
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Recursion with memoO(n)
- Bottom-up tableO(n)
- Two variablesO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100 houses | Verdict |
|---|---|---|---|
| Recursion with memo | O(n) | Passes; clearest recurrence | |
| Bottom-up table | O(n) | Passes; no recursion | |
| Two variables | O(n) | Best; constant memory |
n = number of houses. All three do O(n) steps; the bars reflect call and memory overhead.
Edge cases to test
- One house. [7] gives 7; make sure the table version does not read past the end.
- Two houses. [2, 6] gives 6: take the bigger one.
- Skipping two in a row. [5, 1, 1, 5] gives 10; the best plan is not every other house.
- Empty houses. [0, 0, 0] gives 0.
Common mistakes
- Summing every other house (even or odd positions) and taking the larger, which fails on [5, 1, 1, 5].
- Writing the recursion without a memo, which takes exponential time on 100 houses.
- Updating
prevbefore using it, so the new best is built from the wrong total.
How to talk through it
- 1Clarify. Can the list have one house? Can money be zero? Are only direct neighbours forbidden?
- 2State the choice. At each house: skip it and keep the best so far, or take it and add it to the best from two houses back.
- 3Write the recurrence. best(i) = max(best(i + 1), nums[i] + best(i + 2)); say that a memo makes it O(n).
- 4Shrink the memory. Each value needs only the previous two, so keep prev and cur instead of a table.
- 5Test out loud. Run [7], [2, 6] and [5, 1, 1, 5] before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?