AlgoFrames

House robber in two variables

Standard · Write code · about 10 min

Houses stand in a row and nums[i] is the money in house i. Robbing two neighbouring houses sets off an alarm.

Return the most money you can take without robbing two neighbours. Use O(1) extra memory: no array of size n.

Example 1

Input:

[[2,7,9,3,1]]

Output:

12

Houses 0, 2 and 4: 2 + 9 + 1 = 12.

Example 2

Input:

[[1,2,3,1]]

Output:

4

Houses 0 and 2: 1 + 3 = 4.

Constraints

  • 0 ≤ nums.length ≤ 1,000
  • 0 ≤ nums[i] ≤ 400

Learn the idea first: Space optimization: rolling rows and variables, a visual lesson.

More Space optimization: rolling rows and variables problems