Practice · Dynamic programming (1D) · 5 of 8

Rob a Row of Houses

A street has a row of houses, and nums[i] is the amount of money in house i. You may rob any houses you like, except that robbing two houses that stand next to each other sets off an alarm.

Return the largest total you can take without robbing two neighbouring houses.

Example 1

Input
nums = [2, 7, 9, 3, 1]
Output
12
Rob houses 0, 2 and 4: 2 + 9 + 1 = 12.

Example 2

Input
nums = [5, 1, 1, 5]
Output
10
Rob the first and last houses. Skipping two houses in a row is allowed.

Constraints

  • nums holds 1 to 2000 numbers.
  • 0 ≤ nums[i] ≤ 1000