Skip to content
mlmentorship

Compare skipping the current item with its last compatible prefix

Name the two prefix optima, derive skip versus take, then change endpoint conflicts or recover selected indices.

Published · 17 min read ·Core ·Intermediate

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

Compare skipping the current item with its last compatible prefix

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

Problem

Input. An integer list nums giving house values in linear street order. Output. Return the largest sum over selections containing no two adjacent positions. Rules. The first and last houses are not neighbors unless they are consecutive in the list. Selecting no houses is allowed, so empty and all-negative inputs return zero. Return only the total, not the selected indices. Preserve the input. Example. [2, 7, 9, 3, 1] returns 12, achieved by indices [0, 2, 4]. Taking 7 and 9 together is forbidden because their positions are adjacent.

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

For each prefix, compare skipping the current house with taking it after the last compatible prefix.

Taking house 3 excludes house 2 and reuses only the earlier optimum

Taking the current house excludes its immediate neighborFor values (2,7,9,3), skipping house 3 keeps 11. Taking it adds 3 only to the earlier optimum 7, giving 10.Taking the last house excludes itsimmediate neighborSkip house three: keep houses zeroand two2793Total 11Take house three: earlier safe prefixseven + three2793Total 10
Read it this way: For values (2,7,9,3), skipping house 3 keeps 11. Taking it adds 3 only to the earlier optimum 7, giving 10. Can taking house three add its value to the eleven that already includes neighboring house two?
Full interview answer 17 min read

Choose nonadjacent houses along a street to maximize the total value collected.

Problem

Input. An integer list nums giving house values in linear street order.

Output. Return the largest sum over selections containing no two adjacent positions.

Rules. The first and last houses are not neighbors unless they are consecutive in the list. Selecting no houses is allowed, so empty and all-negative inputs return zero. Return only the total, not the selected indices. Preserve the input.

Example. [2, 7, 9, 3, 1] returns 12, achieved by indices [0, 2, 4]. Taking 7 and 9 together is forbidden because their positions are adjacent.

Picture

At index 3, taking value 3 excludes index 2. It can extend the best prefix through index 1, not the immediately preceding prefix.

Reference drawing

Taking house 3 excludes house 2 and reuses only the earlier optimum

Taking the current house excludes its immediate neighborFor values (2,7,9,3), skipping house 3 keeps 11. Taking it adds 3 only to the earlier optimum 7, giving 10.Taking the last house excludes itsimmediate neighborSkip house three: keep houses zeroand two2793Total 11Take house three: earlier safe prefixseven + three2793Total 10
Derivation
Taking house 3 can reuse only the optimum through house 1The pictured house values are two, seven, nine, and three at indices zero through three. Skipping house three keeps houses zero and two, totaling eleven. Taking house three can add only the best through index one, seven, giving ten. The adjacent houses two and three are never combined.Evaluate house 3; neighbors cannot both betaken2index 07index 19index 23index 3SKIP house 3: keep houses 0 + 2 = 11TAKE house 3: best through 1 is 7; 7 + 3 = 10max(11, 10) = 11; never combine adjacent 2 and3
The take branch stops its reusable prefix two houses back. The skip branch keeps eleven. Their maximum is eleven, without using adjacent houses.
Read it this way: For values (2,7,9,3), skipping house 3 keeps 11. Taking it adds 3 only to the earlier optimum 7, giving 10. Can taking house three add its value to the eleven that already includes neighboring house two?

These cases are exhaustive: a selection either contains the current position or does not. Neither saved prefix optimum must select its last position. Taking the current value after the two-back optimum is compatible; skipping preserves the one-back optimum.

Problem trace

Read both old prefix optima before committing the better skip or compatible take

Input and goalFind the most money that can be taken without choosing neighboring houses.
Initialize before house 0For money [2, 7, 9, 3, 1], both saved prefix answers start at zero.
next i=0house 0: $20house 1: $71house 2: $92house 3: $33house 4: $14
statetwo_houses_back=0, one_house_back=0meaningbest totals before any house
next i
0
state
two_houses_back=0, one_house_back=0
meaning
best totals before any house

Recognize it
Items lie in a line, adjacent choices conflict, and the objective asks for a maximum total rather than the exact chosen sequence.
Keep true
Before house i, one_house_back is the optimum for houses through i - 1 and two_houses_back is the optimum through i - 2. Therefore max(one_back, two_back + money[i]) is the complete optimum through i.
Reuse it
When choosing item i only conflicts with a fixed neighborhood, compare the optimum that excludes i with value[i] plus the last compatible optimum. This transfers to weighted independent sets on paths and cooldown scheduling.
For money [2, 7, 9, 3, 1], both saved prefix answers start at zero. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: At house 2, why is the take candidate 2 + 9 rather than 7 + 9?

Problem trace

Read both old prefix optima before committing the better skip or compatible take

Read both old prefix optima before committing the better skip or compatible takeBoth totals are prefix optima, not promises to select their last houses. Skip preserves the previous optimum; take extends the prefix before the neighbor. Read both old values before shifting. The five prefix results are two, seven, eleven, eleven and twelve. At three, skip keeps eleven; compatible take gives ten. An early shift incorrectly gives fourteen using adjacent houses. Empty and negative-only inputs permit zero. Recovering indices requires history; changing exclusion distance changes the dependency.Read compatible old prefixes beforeeither state shiftsThe two-back total need not selectits final house. A total alone is nota stored witness.index 02index 17index 29index 33index 41At index 0, value 2Old prefix optima: two-back 0;one-back 0.Skip 0; compatible take 2; commit 2.At index 1, value 7Old prefix optima: two-back 0;one-back 2.Skip 2; compatible take 7; commit 7.At index 2, value 9Old prefix optima: two-back 2;one-back 7.Skip 7; compatible take 11; commit11.At index 3, value 3Old prefix optima: two-back 7;one-back 11.Skip 11; compatible take 10; commit11.At index 4, value 1Old prefix optima: two-back 11;one-back 11.Skip 11; compatible take 12; commit12.Actual feasible branches at indexthreeSkip: retain the eleven-valued prefix0:21:72:93:3Checked indices 0, 2; total 11.Take: old safe prefix seven, thenthree0:21:72:93:3Checked indices 1, 3; total 10.Wrong early shift: eleven plus threegives fourteen, keeping indices zero,two and three. The last two areadjacent.Changed exclusion: skip the precedingthree positions. Taking index fourcan extend only the prefix throughzero; this input now has optimumnine.Linear updates, two scalar slots;input unchanged. Integer-size costsare separate. Recover a plan withprefix history and a declared tierule.
Read it this way: Both totals are prefix optima, not promises to select their last houses. Skip preserves the previous optimum; take extends the prefix before the neighbor. Read both old values before shifting. The five prefix results are two, seven, eleven, eleven and twelve. At three, skip keeps eleven; compatible take gives ten. An early shift incorrectly gives fourteen using adjacent houses. Empty and negative-only inputs permit zero. Recovering indices requires history; changing exclusion distance changes the dependency. May taking three extend eleven?
Reference drawing

Problem trace

Read both old prefix optima before committing the better skip or compatible take

Read both old prefix optima before committing the better skip or compatible takeBoth totals are prefix optima, not promises to select their last houses. Skip preserves the previous optimum; take extends the prefix before the neighbor. Read both old values before shifting. The five prefix results are two, seven, eleven, eleven and twelve. At three, skip keeps eleven; compatible take gives ten. An early shift incorrectly gives fourteen using adjacent houses. Empty and negative-only inputs permit zero. Recovering indices requires history; changing exclusion distance changes the dependency.Read compatible old prefixes beforeeither state shiftsThe two-back total need not selectits final house. A total alone is nota stored witness.index 02index 17index 29index 33index 41At index 0, value 2Old prefix optima: two-back 0;one-back 0.Skip 0; compatible take 2; commit 2.At index 1, value 7Old prefix optima: two-back 0;one-back 2.Skip 2; compatible take 7; commit 7.At index 2, value 9Old prefix optima: two-back 2;one-back 7.Skip 7; compatible take 11; commit11.At index 3, value 3Old prefix optima: two-back 7;one-back 11.Skip 11; compatible take 10; commit11.At index 4, value 1Old prefix optima: two-back 11;one-back 11.Skip 11; compatible take 12; commit12.Actual feasible branches at indexthreeSkip: retain the eleven-valued prefix0:21:72:93:3Checked indices 0, 2; total 11.Take: old safe prefix seven, thenthree0:21:72:93:3Checked indices 1, 3; total 10.Wrong early shift: eleven plus threegives fourteen, keeping indices zero,two and three. The last two areadjacent.Changed exclusion: skip the precedingthree positions. Taking index fourcan extend only the prefix throughzero; this input now has optimumnine.Linear updates, two scalar slots;input unchanged. Integer-size costsare separate. Recover a plan withprefix history and a declared tierule.
Execution trace
Input and goalFind the most money that can be taken without choosing neighboring houses.
Initialize before house 0For money [2, 7, 9, 3, 1], both saved prefix answers start at zero.
next i=0house 0: $20house 1: $71house 2: $92house 3: $33house 4: $14
statetwo_houses_back=0, one_house_back=0meaningbest totals before any house
next i
0
state
two_houses_back=0, one_house_back=0
meaning
best totals before any house

Recognize it
Items lie in a line, adjacent choices conflict, and the objective asks for a maximum total rather than the exact chosen sequence.
Keep true
Before house i, one_house_back is the optimum for houses through i - 1 and two_houses_back is the optimum through i - 2. Therefore max(one_back, two_back + money[i]) is the complete optimum through i.
Reuse it
When choosing item i only conflicts with a fixed neighborhood, compare the optimum that excludes i with value[i] plus the last compatible optimum. This transfers to weighted independent sets on paths and cooldown scheduling.
For money [2, 7, 9, 3, 1], both saved prefix answers start at zero. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: At house 2, why is the take candidate 2 + 9 rather than 7 + 9?
Read it this way: Both totals are prefix optima, not promises to select their last houses. Skip preserves the previous optimum; take extends the prefix before the neighbor. Read both old values before shifting. The five prefix results are two, seven, eleven, eleven and twelve. At three, skip keeps eleven; compatible take gives ten. An early shift incorrectly gives fourteen using adjacent houses. Empty and negative-only inputs permit zero. Recovering indices requires history; changing exclusion distance changes the dependency. May taking three extend eleven?

After each value, the prefix optima are 2,7,11,11,12. Compute current before shifting either dependency.

Code

def house_robber(nums: list[int]) -> int:
   two_houses_back = 0
   one_house_back = 0

   for money in nums:
      current = max(one_house_back, two_houses_back + money)
      two_houses_back, one_house_back = one_house_back, current

   return one_house_back

At value 9, taking gives 2+9=11, beating 7. At value 3, skipping keeps 11, beating 7+3=10. At value 1, taking gives 11+1=12. The displayed indices are a checked witness, not state retained by this function.

There are scalar updates and scalar slots, excluding input and integer-size costs. Greedily choosing a locally larger value does not compare the required compatible prefix optima. An arbitrary conflict graph does not share this line-prefix guarantee.

Change the Endpoint Conflict

New task: First and last positions also conflict.

Picture and change: At least one endpoint must be excluded. Compare the line without the last position against the line without the first. Handle a single position separately.

def circular_robber(nums):
   if not nums:
      return 0
   if len(nums) == 1:
      return max(0, nums[0])
   return max(house_robber(nums[:-1]), house_robber(nums[1:]))

Check: [2,3,2] returns 3; its two endpoint values cannot be combined. [-1] returns 0. Python slices add storage despite each line computation’s two saved scalars.

Use when: Only endpoint compatibility changes.

Change the Required Output

New task: Return the total and selected indices.

Picture and change: Retain every prefix optimum, then walk backward. Skip on ties; otherwise take this index and jump over its excluded neighbor.

def robber_with_indices(nums):
   best = [0] * (len(nums) + 1)
   for index, value in enumerate(nums, 1):
      compatible = best[index - 2] if index >= 2 else 0
      best[index] = max(best[index - 1], value + compatible)
   chosen, index = [], len(nums)
   while index > 0:
      if best[index] == best[index - 1]:
         index -= 1
      else:
         chosen.append(index - 1)
         index -= 2
   return best[-1], chosen[::-1]

Check: [2,7,9,3,1] returns (12,[0,2,4]); [0,0] returns (0,[]). Selected values must sum to the reported optimum, with no adjacent indices. This reconstruction retains table slots plus its output. Several witnesses can be optimal; the tie policy selects one deterministically.

Use when: The decision must be recovered, not only its value.

Transfer Check

What changes if selecting index i excludes the preceding three positions?

Answer

The take branch needs the optimum through i-4. The skip branch still uses the preceding prefix optimum. The compatibility horizon and retained state must expand.