Fundamentals 5 min read

Master the House Robber Problem with Dynamic Programming

This article explains the classic House Robber interview question, detailing the problem constraints, illustrating why a naive alternating‑house approach fails, and presenting a clear dynamic‑programming solution with recurrence, base cases, and a concise code example.

NiuNiu MaTe
NiuNiu MaTe
NiuNiu MaTe
Master the House Robber Problem with Dynamic Programming

Problem Statement

Given an array of non‑negative integers where each element represents the amount of money in a house, determine the maximum amount that can be stolen without robbing two adjacent houses on the same night.

Example

Input: [3,2,1,2]

Output: 5

Choosing houses 0 and 3 yields 5, which is better than the naive alternating choice that would only give 4.

Analysis

Because adjacent houses are mutually exclusive, the problem cannot be solved by a fixed‑interval pattern; instead it requires considering two cases for each house: either it is robbed (and the previous house cannot be) or it is skipped.

Dynamic Programming Solution

Define dp[i] as the maximum amount that can be obtained from the first i+1 houses.

Recurrence: dp[i] = max(dp[i-1], dp[i-2] + nums[i]) Base cases:

dp[0] = nums[0]
dp[1] = max(nums[0], nums[1])

This recurrence captures the two possibilities: skipping the current house ( dp[i-1]) or robbing it ( dp[i-2] + nums[i]).

Code Example

Dynamic programming implementation for the House Robber problem
Dynamic programming implementation for the House Robber problem

Conclusion

The House Robber problem is a textbook example of using dynamic programming to transform a combinatorial optimization problem into a linear‑time solution by building on previously computed sub‑problems.

algorithmdynamic programmingDPinterview questionhouse robber
NiuNiu MaTe
Written by

NiuNiu MaTe

Joined Tencent (nicknamed "Goose Factory") through campus recruitment at a second‑tier university. Career path: Tencent → foreign firm → ByteDance → Tencent. Started as an interviewer at the foreign firm and hopes to help others.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.