DSA Tracker

Medium

House Robber

A medium Dynamic Programming problem included in Apna College, Love Babbar 450, Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.

Topic
Dynamic Programming
Sheets
3
Core for
9 roles
Platform
LeetCode

The problem

You are given an array of non-negative integers representing the amount of money in each house. You cannot rob adjacent houses. Find the maximum amount of money you can steal without alerting the police.

Example 1

Input
nums = [1,2,3,1]
Output
4
Why
Rob house 1 (money 1) and house 3 (money 3), total = 4.

Example 2

Input
nums = [2,7,9,3,1]
Output
12
Why
Rob house 1 (2), house 3 (9), and house 5 (1), total = 12.

Example 3

Input
nums = [2,1,1,2]
Output
4
Why
Rob house 1 (2) and house 4 (2), total = 4.

Constraints

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 400

How to think about it

Updated 2026-09-09

At each house, you have exactly two choices: rob it and collect its loot plus the best total from two houses back, or skip it and keep whatever was best up to the previous house. You only need to remember the best results from the previous two steps to make the next call.

Approaches, worst first

  1. Recursive exploration

    time O(2^n) · space O(n)

    Recurse from index i with branches for robbing (i + 2) or skipping (i + 1). Without memoization this repeats the exact same sub-array calculations on every path.

  2. Linear table

    time O(n) · space O(n)

    Maintain an array dp of length n. Set dp[0] = nums[0] and dp[1] = max(nums[0], nums[1]). For each house i >= 2, dp[i] = max(dp[i-1], dp[i-2] + nums[i]).

  3. Constant space rolling variablesWrite this one

    time O(n) · space O(1)

    Replace the array with two scalar variables, prev1 and prev2, tracking the max loot obtained one step and two steps prior. On each house, new_loot = max(prev1, prev2 + nums[i]), then roll the variables forward.

Where people lose marks · 3
  • Crashing on arrays with length 1 or 2 when indexing dp[i-2] without proper guard conditions or initial values.
  • Choosing greedily based on the largest house values. Picking a high-value house might lock out two adjacent houses whose combined value is greater.
  • Assuming alternating houses (all evens or all odds) is optimal. One can legally skip two houses in a row (e.g., house 0 then house 3) to pick up a much larger reward.

Full solution

Constant-space rolling variables (the notes' recommended approach): only the best loot from one and two houses back is ever needed, so the O(n) dp array collapses to two scalars.

Python
def rob(nums: list[int]) -> int:
    # Rolling registers: best loot using houses up to i-2 and up to i-1.
    prev2, prev1 = 0, 0
    for n in nums:
        prev2, prev1 = prev1, max(prev1, prev2 + n)
    return prev1
JavaScript
function rob(nums) {
  let prev2 = 0, prev1 = 0;
  for (const n of nums) {
    [prev2, prev1] = [prev1, Math.max(prev1, prev2 + n)];
  }
  return prev1;
}
Try it in the editor

The theory behind it

Dynamic Programming — the ground this problem stands on. All Dynamic Programming problems

What Dynamic Programming is

Dynamic programming is a method for solving a complex problem by breaking it into overlapping subproblems, solving each subproblem only once, and remembering the answers in a lookup table. Instead of recalculating identical questions over and over, future steps look up previous answers directly. By assembling these saved pieces from the bottom up or storing them during recursion, a task that would take billions of steps finishes in a fraction of a second.

When to reach for it

Reach for dynamic programming when questions ask for the maximum profit, minimum cost, total number of distinct ways to achieve a goal, or whether a target can be formed. Signals include overlapping choices where making a choice now affects what choices remain later, but greedy picking fails to find the true global optimum. If drawing a recursive decision tree reveals the same subproblem states repeating across branches, dynamic programming is needed.

How the pattern works

Identify the state variables that uniquely describe a subproblem, such as an array index and remaining capacity. Write the base cases first, representing states whose answers are known without calculation. Next, write the recurrence relation that expresses the current state using previously solved states, taking the minimum, maximum, or sum among your options. Build the solution either top-down by caching recursive returns in a memo table, or bottom-up by filling an array in topological dependency order. When each state depends only on the previous row, compress storage down to a single array.

What each operation costs

OperationTime
fill dynamic programming table of n statesO(n)
solve two-dimensional grid of m by n statesO(m * n)
space-optimized state transition keeping one rowO(n)
What usually goes wrong with Dynamic Programming
  • Filling a bottom-up table in an order where the current cell needs values that have not been computed yet, reading uninitialized zeros.
  • Failing to initialize base cases properly, such as filling a minimization table with zeros instead of infinity, which traps the answer at zero.
  • Overwriting values in a 1D space-optimized knapsack array by scanning in the wrong direction, allowing the same item to be chosen multiple times.

Which roles need this problem

Dynamic Programming is a core topic for these 9 roles — if you're targeting one of them, this problem is early in your path, not optional.

Secondary for 5 more roles, including Game Developer, Cryptography Engineer, Performance Engineer.

Track this in your role's order

Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.

Start free

More Dynamic Programming problems

Problem set and role mapping as of .