</>

198. House Robber

Medium NeetCode 150
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
1-D Dynamic Programming
Time
—
Space
—

Standard Solution (C++)

SummaryGiven a row of houses each holding some amount of money, find the maximum total you can steal without ever robbing two directly adjacent houses.

Approach
  • At each house, the robber faces exactly two choices: skip it (carry forward the best result so far) or rob it (add its value to the best result two houses back).
  • This recurrence — dp[i] = max(dp[i-1], nums[i] + dp[i-2]) — captures all valid non-adjacent subsets.
  • Because each step only needs the previous two values, two rolling variables replace the full DP array, giving O(1) space.
  • A single left-to-right pass suffices because every subproblem is resolved before it is needed.
#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public:
    int rob(vector<int>& nums) {
        // prev2 = best loot up to two houses ago
        // prev1 = best loot up to the previous house
        int prev2 = 0, prev1 = 0;

        for (int money : nums) {
            // Either skip this house (prev1) or rob it (money + prev2)
            int cur = max(prev1, money + prev2);
            prev2 = prev1;
            prev1 = cur;
        }

        return prev1;
    }
};
Time O(n) Space O(1)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

#include <vector>
using namespace std;

class Solution {
public:
    int rob(vector<int>& nums) {
        int prev1=0;
        int prev2=0;

        for(const int n: nums){
            int cur=std::max(prev1, n+prev2);
            prev2=prev1;
            prev1=cur;
        }

        return prev1;
    }
};

// Time: O(N)
// Space: O(1)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern