SprintCode.pro

Подготовка к алгоритмическим задачам

Super

House Robber

Description: Given money in houses standing in a row, you cannot rob two adjacent houses. Return the maximum amount you can take.

Example 1:

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

Example 2:

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

Constraints:

1 <= nums.length <= 100

0 <= nums[i] <= 400

Recommended time and space complexity

Aim for O(n) time and O(1) space.


Hint 1

For each house there are two options: rob it or skip it.


Hint 2

Robbing house i adds the best result up to i−2; skipping takes the best up to i−1.


Hint 3

Only two previous values are needed — no array required.

A one-dimensional dynamic programming problem with an adjacency constraint. Teaches the take-or-skip choice and O(1) memory.

Expected Input :

[2,7,9,3,1]

Expected Output

12