iq.lab
Python starts when a code cell comes near or you run one
mediumDynamic programming, 1D target 25 min

Houses in a circle

A thief plans one night on a street of houses built in a circle. money[i] is the cash in house i. Each house is next to the houses on either side of it, and because the street closes into a circle, the last house is also next to house 0. Robbing two houses that stand next to each other sets off an alarm, so the thief never robs two neighbors.

Return the most cash the thief can collect. A street with a single house has no neighbors to worry about.

Example 1
Inputmoney = [4, 1, 2, 6]Output7

Houses 1 and 3: 1 + 6 = 7. Houses 0 and 3 would give 10, but they are neighbors around the circle.

Example 2
Inputmoney = [6, 4, 5, 2]Output11

Houses 0 and 2: 6 + 5. The circle does not get in the way here.

Example 3
Inputmoney = [5, 5, 5, 5, 5]Output10

On a straight street, houses 0, 2 and 4 would give 15, but houses 0 and 4 are neighbors now. At most two of five houses in a circle can be robbed.

Constraints
  • 1 ≤ len(money) ≤ 100

  • 0 ≤ money[i] ≤ 500

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.