Parcel-delivery app~20 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-1208sliding-window-variable
A parcel-delivery app plans each region's deliveries as one long sequence of stops for the day. Every stop has a handling time in minutes, for unloading, scanning and getting a signature. Lockers need no handling time at all.
Planners want to give one driver the longest possible run of consecutive stops whose handling time fits inside a shift budget. Driving time is planned separately, so only handling time counts here.
Write longest_run(minutes, shift).
minutes[i] is the handling time of stop i, in order along the sequence.shift.0.Input: minutes = [2, 1, 3, 7, 1, 1, 2, 1], shift = 7
Output: 4| right | Joins | Total after joining | Leaves while over 7 | Run | Length | Best |
|---|---|---|---|---|---|---|
| 0 | 2 | 2 | none | 2 | 1 | 1 |
| 1 | 1 | 3 | none | 2, 1 | 2 | 2 |
| 2 | 3 | 6 | none | 2, 1, 3 | 3 | 3 |
| 3 | 7 | 13 | 2, 1, 3 (total 11, 10, 7) | 7 | 1 | 3 |
| 4 | 1 | 8 | 7 (total 1) | 1 | 1 | 3 |
| 5 | 1 | 2 | none | 1, 1 | 2 | 3 |
| 6 | 2 | 4 | none | 1, 1, 2 | 3 | 3 |
| 7 | 1 | 5 | none | 1, 1, 2, 1 | 4 | 4 |
When the 7-minute stop joins, three stops must leave before the run fits again. The best run is the last four stops.
Input: minutes = [9, 4], shift = 3
Output: 0Every stop alone needs more than the shift allows.
Input: minutes = [0, 0, 5, 0], shift = 0
Output: 2Lockers take no time, so the first two stops fit even a budget of 0.
1 ≤ minutes.length ≤ 10^5 (all the stops of a large region's day)0 ≤ minutes[i] ≤ 10^40 ≤ shift ≤ 10^9Trying every start and every end is about n^2 / 2 = 5 × 10^9 pairs. That is far too slow, so aim for O(n).
The values matter more here. Handling times are never negative, so adding a stop never makes a run shorter in time. That property is what lets a window shrink safely from the left.