Ad platform~20 min2s · 256 MBtarget O(n + q) time, O(n) spaceclassic twin: lc-370difference-array
An ad platform sells slots on a page, and each slot has a base price in units. The sales team then sends many adjustments. One adds a surcharge to a run of slots, and another gives a discount to a run of slots.
The final rate card is published once, after every adjustment is applied. A card has up to 100,000 slots, and up to 100,000 adjustments arrive in a day.
Write adjust_rate_card(prices, adjustments).
prices[i] is the base price of slot i. Slots are numbered from 0.adjustments[j] is [first, last, delta] with 0 <= first <= last < len(prices). It adds delta to every slot from first to last, both included. delta can be negative.Input: prices = [8, 5, 9, 4, 6, 7, 3], adjustments = [[1, 3, 2], [0, 6, -1], [4, 5, 4]]
Output: [7, 6, 10, 5, 9, 10, 2]Write two notes for each adjustment, then add up the notes and add the base prices.
| Slot | Change | Running total | Base price | Final price |
|---|---|---|---|---|
| 0 | -1 | -1 | 8 | 7 |
| 1 | +2 | 1 | 5 | 6 |
| 2 | 0 | 1 | 9 | 10 |
| 3 | 0 | 1 | 4 | 5 |
| 4 | +2 | 3 | 6 | 9 |
| 5 | 0 | 3 | 7 | 10 |
| 6 | -4 | -1 | 3 | 2 |
The change list is [-1, 2, 0, 0, 2, 0, -4, 1]. The last entry is never read.
Input: prices = [5], adjustments = [[0, 0, -5]]
Output: [0]A discount of the whole price.
Input: prices = [1, 2, 3], adjustments = [[0, 2, 10], [2, 2, 5]]
Output: [11, 12, 18]The second adjustment reaches the last slot.
1 ≤ prices.length ≤ 100,000 and 0 ≤ prices[i] ≤ 1,000,000 (units)1 ≤ adjustments.length ≤ 100,0000 ≤ first ≤ last < prices.length and -100,000 ≤ delta ≤ 100,000An adjustment can cover the whole card. With 100,000 slots and 100,000 adjustments, adding to every slot costs up to 10^10 additions.
Two writes for each adjustment and one pass cost about 3 × 10^5 steps. Prices can reach 10^10, so use 64-bit integers.