Workspace House Robber
0d
Back to questionsDSA Visualizers: 388 Coding Questions

House Robber visualizer

Choose nonadjacent entries of nonnegative value to maximize the total. Return the best sum.

EXECUTION LAB

Choose nonadjacent entries of nonnegative value to maximize the total. Return the best sum.

Input and constraints
  • Each value must be nonnegative.
  • Use at most 32 integers. Each numeric input is between -1000 and 1000.

Code inspector

def solve(values, target):
twoBack = 0
best = 0
i = 0
while (i < len(values)):
nextBest = max(best, (twoBack + values[i]))
twoBack = best
best = nextBest
i = (i + 1)
return best

Visualizer

Step 1 of 6
04i
11
22
37
45

Compare skipping this position with taking it

Compare skipping this position with taking it.

Variable watch

i 0twoBack 0best 0

Step explanation

Compare skipping this position with taking it.

comparisons 1reads 0writes 0swaps 0recursiveCalls 0
Educational simulation · O(n) time · O(1) space

Worked explanation

Pick paid workshops on nonconsecutive days and compare attending today with keeping yesterday’s schedule.

Guided solution

Compare skipping today with taking today plus the best available two positions back.

O(n) time · O(1) auxiliary space

Examples

Worked example · {"values":[4,1,2,7,5],"target":0} ⇒ 11

Edge case 1 · {"values":[],"target":0} ⇒ 0

Edge case 2 · {"values":[3],"target":0} ⇒ 3

Progressive hints

Hint 1Pick paid workshops on nonconsecutive days and compare attending today with keeping yesterday’s schedule.
Hint 2Compare skipping today with taking today plus the best available two positions back.
Hint 3Step through the worked example and inspect the highlighted variables before each update.

Common mistake

Taking every locally larger value can block a better pair later.

Interview follow-up

How would a circular street change the first and last choices?

Continue learning

Practice related DSA questions in the same topic.