Payments app~25 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-209sliding-window-variable
A payments app shows each merchant a short report of milestones. Your team lead wants a new one: "Your fastest run to a target." It shows the fewest consecutive hours in which the merchant ever earned at least a chosen amount.
The data is the merchant's settled revenue for every hour since they joined, in integer units. Refunds are reported separately, so no hour is negative. If the merchant never reached the target in any stretch, the report shows 0.
Write fewest_hours(revenue, target).
revenue[i] is the settled revenue in hour i, in integer units, never negative.target.target, return 0.Input: revenue = [4, 1, 1, 3, 6, 2], target = 8
Output: 2| right | Joins | Total after joining | Recorded, then the left hour leaves | left after | Best |
|---|---|---|---|---|---|
| 0 | 4 | 4 | none | 0 | none |
| 1 | 1 | 5 | none | 0 | none |
| 2 | 1 | 6 | none | 0 | none |
| 3 | 3 | 9 | length 4, then 4 leaves (total 5) | 1 | 4 |
| 4 | 6 | 11 | length 4, 3, 2; then 1, 1, 3 leave (total 10, 9, 6) | 4 | 2 |
| 5 | 2 | 8 | length 2, then 6 leaves (total 2) | 5 | 2 |
The hours 3, 6 reach the target in 2 hours. So do the hours 6, 2.
Input: revenue = [1, 1, 1], target = 5
Output: 0The whole history earns 3, which never reaches 5.
Input: revenue = [0, 9, 0], target = 9
Output: 1One hour is enough.
1 ≤ revenue.length ≤ 10^5 (about 11 years of hours)0 ≤ revenue[i] ≤ 10^61 ≤ target ≤ 10^11Trying every start and adding hours until the target is reached is O(n^2) in the worst case, about 5 × 10^9 steps. Aim for O(n).
Read the values too. A merchant's history can total 10^11 units, and target itself can be 10^11, so both need 64-bit integers in Java and C++. Because no hour is negative, a window that reaches the target can only shrink to find a shorter one.