Ride-hailing app~25 min2s · 256 MBtarget O(n) time, O(n) spacesliding-window-fixed · difference-array
A ride-hailing app counts ride requests for every minute of the day. When the requests in a short stretch of minutes are high, the app raises prices. The rule looks at windows of k consecutive minutes.
If the total requests in a window reach a threshold, every minute of that window is priced as a surge minute. Windows overlap, so a minute can belong to many of them. The app wants to know how many minutes carry a surge price.
Write surging_minutes(demand, k, threshold).
demand[i] is the number of ride requests in minute i.k consecutive minutes whose total requests is at least threshold.Input: demand = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3], k = 3, threshold = 13
Output: 7The trace slides a window of 3 minutes and keeps its total. The windows are numbered by their first minute.
| Window | Minutes | Total | Surge window? |
|---|---|---|---|
| 0 | 0 to 2 | 8 | no |
| 1 | 1 to 3 | 6 | no |
| 2 | 2 to 4 | 10 | no |
| 3 | 3 to 5 | 15 | yes |
| 4 | 4 to 6 | 16 | yes |
| 5 | 5 to 7 | 17 | yes |
| 6 | 6 to 8 | 13 | yes (equal to the threshold) |
| 7 | 7 to 9 | 14 | yes |
The surge windows cover minutes 3 to 9, which is 7 minutes. There are 5 surge windows, but the answer counts minutes, so the output is 7.
Input: demand = [1, 1, 1, 1], k = 2, threshold = 5
Output: 0Every window of 2 minutes has a total of 2, below 5, so no minute surges.
Input: demand = [0, 7, 0, 0, 8, 0], k = 1, threshold = 7
Output: 2With k = 1, each minute is its own window. Minutes 1 and 4 reach 7.
1 ≤ demand.length ≤ 100,000 (minutes in the period)0 ≤ demand[i] ≤ 1,000,000 (ride requests in a minute)1 ≤ k ≤ demand.length (minutes in a window)1 ≤ threshold ≤ 1,000,000,000 (requests)Adding up every window from scratch costs about n × k, up to 2.5 × 10^9 steps for a window of 50,000 minutes. A sliding window updates the total in one step as it moves, and a difference array marks whole ranges of minutes at once. Both together make the work linear: about n steps.