DevPath

← All problems

House Robber

Medium dynamic-programming

Description

Given non-negative amounts along a street, return the maximum you can rob without robbing two adjacent houses.

Constraints

1 <= n <= 100000; amounts >= 0

Examples

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

Output: 12

2 + 9 + 1

Hints (1)
  • At each house choose the best of skipping or taking plus the total two back.

Solutions

Rolling two-variable DP. · Time O(n) · Space O(1)

func rob(nums []int) int {
    prev, curr := 0, 0
    for _, n := range nums {
        take := prev + n
        if curr > take {
            take = curr
        }
        prev, curr = curr, take
    }
    return curr
}

Create a free account to submit solutions, track progress and save problems.

Create account