House Robber
Choose nonadjacent entries of nonnegative value to maximize the total. Return the best sum.
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 bestVisualizer
Step 1 of 6Compare skipping this position with taking it
Compare skipping this position with taking it.
Variable watch
Step explanation
Compare skipping this position with taking it.
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 1
Pick paid workshops on nonconsecutive days and compare attending today with keeping yesterday’s schedule.Hint 2
Compare skipping today with taking today plus the best available two positions back.Hint 3
Step 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?