Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Solve the house robber problem

Maximize the amount a robber can steal from non-adjacent houses using dynamic programming.

Python practice15 minDynamic ProgrammingIntermediateLast updated March 29, 2026

Problem statement

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money represented by a non-negative integer. Adjacent houses have a security system connected — if two adjacent houses are robbed on the same night, the alarms will trigger. Given a list nums where nums[i] is the amount of money at the i-th house, return the maximum amount of money you can rob without robbing two adjacent houses. Implement rob(nums) that returns the maximum possible stolen amount.

Task

Implement a function that returns the maximum sum of non-adjacent numbers from a list using bottom-up DP with O(1) extra space.

Examples

Basic example

Input

rob([1, 2, 3, 1])

Output

4

Rob houses 1 and 3 (1-based): 1 + 3 = 4.

Input format

A list of non-negative integers nums representing money in each house.

Output format

An integer: the maximum amount that can be robbed without robbing adjacent houses.

Constraints

0 <= len(nums) <= 10^5; 0 <= nums[i] <= 10^9. Aim for O(n) time and O(1) extra space.

Samples

Sample 1

Input

[2, 7, 9, 3, 1]

Output

12

Rob houses with amounts 2, 9, and 1 (or 7 and 3): max is 12.