Payments app~40 min2s · 256 MBtarget O(n log n) time, O(n) spaceintervals · heaps
A software product bills customers by the day. A customer can hold several plans at once, for example when they upgrade in the middle of a month and the old plan runs to its end. Each plan has a start day, an end day and a daily rate.
On a day with more than one active plan, the customer pays only the highest daily rate, not the sum. Days with no plan cost nothing. The billing team wants the total charge over all the plans.
Write total_charge(starts, ends, rates).
i is active on the days from starts[i] up to, but not including, ends[i], and has a daily rate of rates[i] units.Input: starts = [0, 2, 5, 8], ends = [6, 4, 9, 10], rates = [10, 30, 20, 5]
Output: 175The plans are:
The cut points are the start and end days: 0, 2, 4, 5, 6, 8, 9, 10. The trace charges each stretch between cut points.
| Stretch | Days | Active plans | Highest rate | Charge |
|---|---|---|---|---|
| 0 to 2 | 2 | A | 10 | 20 |
| 2 to 4 | 2 | A, B | 30 | 60 |
| 4 to 5 | 1 | A | 10 | 10 |
| 5 to 6 | 1 | A, C | 20 | 20 |
| 6 to 8 | 2 | C | 20 | 40 |
| 8 to 9 | 1 | C, D | 20 | 20 |
| 9 to 10 | 1 | D | 5 | 5 |
The total is 175.
Input: starts = [0, 5], ends = [3, 8], rates = [7, 9]
Output: 48The plans cover days 0 to 2 and days 5 to 7. The days in between are free: 3 days at 7 plus 3 days at 9 is 48.
Input: starts = [3], ends = [4], rates = [100]
Output: 100One plan for one day.
1 ≤ starts.length ≤ 100,000 (plans); ends and rates have the same length0 ≤ starts[i] < ends[i] ≤ 1,000,000,000 (days)1 ≤ rates[i] ≤ 1,000 (units a day)You cannot loop over the days: there can be a billion of them, and each day would check every plan. Only the start and end days change which plans are active, so there are at most 2 × 10^5 cut points. Between two cut points the highest rate is constant, so each stretch is one multiplication. The total can reach 10^9 days × 1,000 units, which needs a 64-bit integer.