House Robber

Medium1-D dynamic programming

Houses stand in a row, and nums[i] is the cash kept in house i. A thief can take the cash from any houses he likes, except that he can never take from two houses that stand next to each other: that sets off the alarm.

Return the most cash he can take.

Examples

Example 1
Input:  nums = [3, 10, 4, 2, 9]
Output: 19

Take 10 and 9. Taking every other house (3 + 4 + 9) gives only 16.

Example 2
Input:  nums = [6, 1, 1, 6]
Output: 12

Take the first and the last house, with two houses skipped between them.

Constraints

  • 1 ≤ nums.length ≤ 100
  • 0 ≤ nums[i] ≤ 400

Stuck?

Hint 1

At house i there are two choices: skip it and keep the best total up to house i - 1, or take it and add it to the best total up to house i - 2.

Hint 2

You only ever look two houses back, so keep two running totals and slide them along the row.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 10 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur