House Robber II

MediumDynamic Programming · 1-D DP🧩 1-D Dynamic ProgrammingLeetCode #213 ↗Updated

Problem

Houses stand in a circle; nums[i] is the cash in house i. Robbing two neighbouring houses triggers the alarm, and the first and last houses are neighbours too. Return the maximum amount you can take without setting off the alarm.
Input[2,3,2]Output3
Input[1,2,3,1]Output4
Input[1,2,3]Output3

1 ≤ n ≤ 100  ·  0 ≤ nums[i] ≤ 1000

Try it yourself

Java
class Solution {
    public int rob(int[] nums) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
The circle only forbids taking both house 0 and house n-1. So solve the ordinary line problem twice — on [0..n-2] and on [1..n-1] — and take the larger.
Pattern1-D Dynamic Programming

Instinct The best answer at position i depends only on a few earlier positions (i-1, i-2, ...) - write dp[i] from its predecessors, then roll it into variables.

Memory hack Look back, pick best, roll forward - every step only remembers the last couple of stairs it stood on.

Open the 1-D Dynamic Programming guide →

Approaches

Brute ForceTwo Lines, Plain Recursion

Time O(2n)Space O(n)

For a line [i..end]: either rob house i and jump to i+2, or skip it and go to i+1. Run this on both circle-breaking ranges. The two branches overlap heavily, so work grows exponentially.

Java
public int rob(int[] nums) {
    int n = nums.length;
    if (n == 1) return nums[0];
    return Math.max(best(nums, 0, n - 2), best(nums, 1, n - 1));
}
private int best(int[] nums, int i, int end) {
    if (i > end) return 0;
    return Math.max(nums[i] + best(nums, i + 2, end), best(nums, i + 1, end));
}

Shows the recurrence clearly, but explodes beyond ~40 houses.

At a glance

LevelApproachTimeSpace
Brute ForceTwo Lines, Plain RecursionO(2n)O(n)
BetterTwo Lines, MemoizationO(n)O(n)
OptimalTwo Lines, Rolling VariablesO(n)O(1)
Common pitfalls
  • Forgetting n == 1 — both ranges become empty and you return 0.
  • Using 0 as the memo sentinel — zero-cash ranges get recomputed forever.
  • Sizing the memo by range length but indexing by absolute i → out of bounds.
Interview tips
  • Solve House Robber I first, then reduce the circle to two lines.
  • Explain why two cases suffice: house 0 and n-1 can never both be taken.
  • Reuse one robLine(lo, hi) helper — no array copies needed.
Pattern
Break the cycle into linear cases → circular DP where the wrap-around only couples the two ends.
My notes saved in this browser