Blind 75 · #51 · 1-D Dynamic Programming

House Robber II

MediumDP on two rangesTime O(n)Space O(1)

House Robber II is a medium 1-D Dynamic Programming problem from the Blind 75. The key pattern is dp on two ranges, and a good solution runs in O(n) time.

Problem

Return the maximum sum of non-adjacent house values when the first and last houses are adjacent in a circle.

Examples

Example 1

Input

[2,7,9,3,1]

Output

11

Example 2

Input

[4,6,4]

Output

6

Example 3

Input

[2,4,6,2]

Output

8

Approach

Houses form a circle, so the first and last cannot both be robbed. Run the straight-line solution once without the last house and once without the first, and take the better.

PatternDP on two ranges
TimeO(n)
SpaceO(1)

Watch out for

A single house is its own answer.

More 1-D Dynamic Programming problems