Skip to content
mlmentorship

House Robber II

Cover every circularly valid selection with two endpoint-excluding lines, then avoid slices or reconstruct a nonadjacent original-index witness.

Published · 20 min read ·Core ·Mixed

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

House Robber II

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. A list nums of nonnegative integer house values in circular order. Output. Return the largest sum obtainable by selecting houses without selecting any adjacent pair. Rules. The first and last houses are neighbors, as are consecutive positions. Taking no houses is allowed. Preserve the input. Empty input returns zero; a single house may be selected without conflicting with itself. Example. [2, 3, 2] returns 3, not 4, because the two endpoint houses are neighbors. For [1, 2, 3, 1], return 4 by selecting values 1 and 3 at indices 0 and 2.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Break the circle into two endpoint-excluding lines, run take-or-skip DP on each, and keep the larger result.

Problem trace

Cover the circle with two endpoint-excluding lines; choose one best feasible result

Input and goalHouses form a circle, so the first and last houses are neighbors.
Split the circular constraintA valid plan excludes index three or index zero. Solve case A [1,2,3] and case B [2,3,1].
wrap0:11:22:33:1
Original house values and cursor
first102132last13
casesA excludes index 3; B excludes index 0
first
0
last
3
cases
A excludes index 3; B excludes index 0

Recognize it
Use it when a linear adjacency DP gains one wraparound conflict between the first and last items; every feasible solution must omit at least one endpoint.
Keep true
Within each line, one_back is the best value through the current processed prefix and two_back is the prior prefix optimum; the two cases jointly cover every circularly valid plan.
Reuse it
When one wraparound edge breaks a linear DP, condition on excluding either endpoint, solve the resulting linear instances, and combine their optima.
A valid plan excludes index three or index zero. Solve case A [1,2,3] and case B [2,3,1]. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why must every valid circular plan appear in at least one of the two endpoint-excluding cases?
Full interview answer 20 min read

Choose nonadjacent houses around a circle to maximize the total value collected.

Problem

Input. A list nums of nonnegative integer house values in circular order.

Output. Return the largest sum obtainable by selecting houses without selecting any adjacent pair.

Rules. The first and last houses are neighbors, as are consecutive positions. Taking no houses is allowed. Preserve the input. Empty input returns zero; a single house may be selected without conflicting with itself.

Example. [2, 3, 2] returns 3, not 4, because the two endpoint houses are neighbors. For [1, 2, 3, 1], return 4 by selecting values 1 and 3 at indices 0 and 2.

Picture

For [1,2,3,1], the wraparound edge forbids selecting indices zero and three together.

CaseOriginal indicesPrefix optimaResult
A: exclude last0,1,21,2,44, using indices 0,2
B: exclude first1,2,32,3,33

Each valid circular plan appears in at least one case. Each case’s linear solution also satisfies the circle. Their maximum therefore equals the circular optimum.

The cases overlap: a plan omitting both endpoints belongs to both. The maximum ignores repeated candidates. Adding case counts would double-count them.

Reuse the linear prefix optimum. Before each house, one_back is the optimum through the previous prefix; two_back is the optimum before that prefix’s last house. Neither variable says its last house was chosen.

Take the current value plus old two_back, or skip it and keep old one_back. Update simultaneously and reset both states between cases.

Nodes show index:value. An X marks the excluded endpoint; its incident edges are absent.

Check [2,3,2]: linear selection would take both twos for four, but the circular answer is three.

Problem trace

Cover the circle with two endpoint-excluding lines; choose one best feasible result

Cover the circle with two endpoint-excluding lines; choose one best feasible resultEvery circular plan omits at least one endpoint, so the two lines cover all valid plans. Each line also forbids the wraparound conflict. Here their prefix optima end at four and three; choose four. Plans omitting both endpoints appear twice, so adding is wrong. Reset prefix states between passes. For two, three, two, the circle scores three while the unrestricted line scores four. Saved scalar totals do not retain a selected plan.Two lines cover valid circles withoutrequiring disjoint plansOriginal indices and nonnegativevalues. A colored selection below isa checked witness, not rolling state.0:11:22:33:1The wraparound edge forbids indiceszero and three together.Case A: exclude last; start bothprefix states at zero0:11:22:33:1Indices 0, 1, 2: prefix optima 1, 2,4.Checked selected indices 0, 2; total4.Case B: exclude first; reset bothprefix states0:11:22:33:1Indices 1, 2, 3: prefix optima 2, 3,3.Checked selected indices 2; total 3.Choose four, not combined seven.Middle-only plans occur in bothlines; maximum does not double-countthem.Changed circle two, three, two: bothcases score three. An unrestrictedline takes both endpoint twos forfour, violating the circle.Empty gives zero; a nonnegativesingleton stands alone. Slices costlinear extra storage; index rangesavoid copies. Recovering indicesneeds history.
Read it this way: Every circular plan omits at least one endpoint, so the two lines cover all valid plans. Each line also forbids the wraparound conflict. Here their prefix optima end at four and three; choose four. Plans omitting both endpoints appear twice, so adding is wrong. Reset prefix states between passes. For two, three, two, the circle scores three while the unrestricted line scores four. Saved scalar totals do not retain a selected plan. Can overlapping case answers be added?
Reference drawing

Problem trace

Cover the circle with two endpoint-excluding lines; choose one best feasible result

Cover the circle with two endpoint-excluding lines; choose one best feasible resultEvery circular plan omits at least one endpoint, so the two lines cover all valid plans. Each line also forbids the wraparound conflict. Here their prefix optima end at four and three; choose four. Plans omitting both endpoints appear twice, so adding is wrong. Reset prefix states between passes. For two, three, two, the circle scores three while the unrestricted line scores four. Saved scalar totals do not retain a selected plan.Two lines cover valid circles withoutrequiring disjoint plansOriginal indices and nonnegativevalues. A colored selection below isa checked witness, not rolling state.0:11:22:33:1The wraparound edge forbids indiceszero and three together.Case A: exclude last; start bothprefix states at zero0:11:22:33:1Indices 0, 1, 2: prefix optima 1, 2,4.Checked selected indices 0, 2; total4.Case B: exclude first; reset bothprefix states0:11:22:33:1Indices 1, 2, 3: prefix optima 2, 3,3.Checked selected indices 2; total 3.Choose four, not combined seven.Middle-only plans occur in bothlines; maximum does not double-countthem.Changed circle two, three, two: bothcases score three. An unrestrictedline takes both endpoint twos forfour, violating the circle.Empty gives zero; a nonnegativesingleton stands alone. Slices costlinear extra storage; index rangesavoid copies. Recovering indicesneeds history.
Execution trace
Input and goalHouses form a circle, so the first and last houses are neighbors.
Split the circular constraintA valid plan excludes index three or index zero. Solve case A [1,2,3] and case B [2,3,1].
wrap0:11:22:33:1
Original house values and cursor
first102132last13
casesA excludes index 3; B excludes index 0
first
0
last
3
cases
A excludes index 3; B excludes index 0

Recognize it
Use it when a linear adjacency DP gains one wraparound conflict between the first and last items; every feasible solution must omit at least one endpoint.
Keep true
Within each line, one_back is the best value through the current processed prefix and two_back is the prior prefix optimum; the two cases jointly cover every circularly valid plan.
Reuse it
When one wraparound edge breaks a linear DP, condition on excluding either endpoint, solve the resulting linear instances, and combine their optima.
A valid plan excludes index three or index zero. Solve case A [1,2,3] and case B [2,3,1]. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why must every valid circular plan appear in at least one of the two endpoint-excluding cases?
Read it this way: Every circular plan omits at least one endpoint, so the two lines cover all valid plans. Each line also forbids the wraparound conflict. Here their prefix optima end at four and three; choose four. Plans omitting both endpoints appear twice, so adding is wrong. Reset prefix states between passes. For two, three, two, the circle scores three while the unrestricted line scores four. Saved scalar totals do not retain a selected plan. Can overlapping case answers be added?

Code

def house_robber_two(nums: list[int]) -> int:
   def rob(line: list[int]) -> int:
      two_back = one_back = 0
      for money in line:
         two_back, one_back = one_back, max(one_back, two_back + money)
      return one_back

   if len(nums) == 1:
      return nums[0]
   return max(rob(nums[:-1]), rob(nums[1:]))

Cost: time and space from the two slices. Index ranges can reduce extra space to .

The slices are evaluated sequentially, but peak extra storage is still linear. Negative values are outside this contract: a negative singleton would return that negative value rather than choosing none.

Change Storage or Retain a Plan

Start from house_robber_two. Both adaptations keep the same two-case coverage proof.

  1. Avoid copied slices.

    New task: Keep constant auxiliary slots.

    Picture and change: Pass half-open original-index ranges to the rolling recurrence. Neither pass constructs a sublist.

    Code: Complete replacement:

    def circular_rob_ranges(nums):
       def rob_range(start, end):
          two_back = one_back = 0
          for index in range(start, end):
             two_back, one_back = one_back, max(one_back, two_back + nums[index])
          return one_back
    
       if len(nums) <= 1:
          return nums[0] if nums else 0
       return max(rob_range(0, len(nums) - 1), rob_range(1, len(nums)))

    Check: [2,3,2] returns three. Empty input returns zero. The original values stay unchanged.

    Use when: Memory is constrained. Work remains ; auxiliary state is slots.

  2. Return selected original indices.

    New task: Retain a feasible plan achieving the scalar optimum.

    Picture and change: Save each line’s prefix values. Backtrack: equal adjacent prefix values permit skipping; a strict improvement takes the current index.

    Code: Complete replacement:

    def circular_rob_plan(nums):
       def line_plan(start, end):
          best = [0] * (end - start + 1)
          for offset in range(1, len(best)):
             before_neighbor = best[offset - 2] if offset > 1 else 0
             best[offset] = max(
                best[offset - 1], before_neighbor + nums[start + offset - 1]
             )
          selected, offset = [], len(best) - 1
          while offset > 0:
             if best[offset] == best[offset - 1]:
                offset -= 1
             else:
                selected.append(start + offset - 1)
                offset -= 2
          return best[-1], list(reversed(selected))
    
       if len(nums) <= 1:
          return [0] if nums and nums[0] > 0 else []
       first = line_plan(0, len(nums) - 1)
       second = line_plan(1, len(nums))
       return first[1] if first[0] >= second[0] else second[1]

    Check: [1,2,3,1] returns [0,2]; [2,3,2] returns [1]. Zero-valued ties may select nothing.

    Use when: A value alone is insufficient. Prefix history and reconstruction use storage and work. Ties skip the current house within a line and prefer case A between lines; no unique-optimum claim is implied.

Rebuild Case Coverage

Why combine these overlapping cases by max, not automatically by addition?

Answer: An optimum needs one best feasible candidate. Counting requires disjoint cases or an explicit overlap correction.