AAlgoLoopSpaced repetition for LeetCode
MEDIUMDynamic ProgrammingLeetCode ↗

House Robber

The key idea

At each house you choose the better of two options: skip it and keep the best total up to the previous house, or rob it and add its money to the best total from two houses back. Tracking just those two running bests gives an O(1)-space scan.

Problem

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. The only constraint stopping you from robbing each of them is that adjacent houses have security systems connected, and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given an integer array nums representing the amount of money of each house, return *the maximum amount of money you can rob tonight* without alerting the police.

Constraints

Examples

Input: nums = [1,2,3,1] Output: 4
Input: nums = [2,7,9,3,1] Output: 12

Complexity

Time: O(n) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More Dynamic Programming problems