Predict the output
What does this print?
spend, budget = [2, 1, 3, 4, 1, 1, 2], 5
total = left = best = 0
for right, x in enumerate(spend):
total += x
while total > budget:
total -= spend[left]
left += 1
best = max(best, right - left + 1)
print(best, left)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 3 4
Right: the days [4, 1] then [1, 1, 2] fit; the last window starts at index 4 and has length 3.
The best run [1, 1, 2] totals 4, and the earlier run [2, 1] is shorter, so the answer and the final left pointer come from the end of the list.
Why not the others?
- B 2 4. The window [1, 1, 2] at the end totals 4, which fits, so the best length reaches 3.
- C 3 0. The left pointer moves forward several times; it ends at index 4.
Steps come from running the Python solution.
Text version
Budget 5:
Cells: [2, 1, 3, 4, 1, 1, 2]
- L = 0, R = 0. Window total = 2. Add day 0: total 2; best 1
- L = 0, R = 1. Window total = 3. Add day 1: total 3; best 2
- L = 0, R = 2. Window total = 6. Add day 2: total 6
- L = 1, R = 2. Window total = 4. Over 5: drop a day, total 4
- L = 1, R = 3. Window total = 8. Add day 3: total 8
- L = 2, R = 3. Window total = 7. Over 5: drop a day, total 7
- L = 3, R = 3. Window total = 4. Over 5: drop a day, total 4
- L = 3, R = 4. Window total = 5. Add day 4: total 5
- L = 3, R = 5. Window total = 6. Add day 5: total 6
- L = 4, R = 5. Window total = 2. Over 5: drop a day, total 2
- L = 4, R = 6. Window total = 4. Add day 6: total 4; best 3
Result: 3
Budget 8:
Cells: [2, 1, 3, 4, 1, 1, 2]
- L = 0, R = 0. Window total = 2. Add day 0: total 2; best 1
- L = 0, R = 1. Window total = 3. Add day 1: total 3; best 2
- L = 0, R = 2. Window total = 6. Add day 2: total 6; best 3
- L = 0, R = 3. Window total = 10. Add day 3: total 10
- L = 1, R = 3. Window total = 8. Over 8: drop a day, total 8
- L = 1, R = 4. Window total = 9. Add day 4: total 9
- L = 2, R = 4. Window total = 8. Over 8: drop a day, total 8
- L = 2, R = 5. Window total = 9. Add day 5: total 9
- L = 3, R = 5. Window total = 6. Over 8: drop a day, total 6
- L = 3, R = 6. Window total = 8. Add day 6: total 8; best 4
Result: 4