Online store~15 min2s · 256 MBtarget O(n + q) time, O(n) spaceclassic twin: lc-303prefix-sums
An online store keeps one number for every day: the units sold that day. The reports page lets an analyst pick two days and see the total sold between them, with both days included.
One analyst opens the page and tries many ranges in a row. The sales numbers do not change while the page is open. Each answer must appear at once, even with 100,000 days of history and 100,000 questions.
Write range_totals(sales, queries).
sales[i] is the number of units sold on day i. Days are numbered from 0.queries[j] is [first, last], with first <= last. It asks for the total of sales[first] to sales[last], both included.Input: sales = [6, 1, 8, 3, 5, 2, 9, 4], queries = [[1, 3], [0, 7], [4, 4]]
Output: [12, 38, 5]Build the prefix list once, then answer each question with one subtraction.
| Question | Entries used | Subtraction | Total |
|---|---|---|---|
| [1, 3] | prefix[4] and prefix[1] | 18 - 6 | 12 |
| [0, 7] | prefix[8] and prefix[0] | 38 - 0 | 38 |
| [4, 4] | prefix[5] and prefix[4] | 23 - 18 | 5 |
The prefix list is [0, 6, 7, 15, 18, 23, 25, 34, 38].
Input: sales = [9], queries = [[0, 0]]
Output: [9]One day, one question.
Input: sales = [0, 0, 0, 7], queries = [[0, 2], [3, 3]]
Output: [0, 7]Days with no sales add nothing.
1 ≤ sales.length ≤ 100,000 (days of history)0 ≤ sales[i] ≤ 1,000,000 (units sold in one day)1 ≤ queries.length ≤ 100,0000 ≤ first ≤ last < sales.length for every questionWith 100,000 days and 100,000 questions, adding up each range costs up to 10^10 additions. That is far too slow. A linear build plus one subtraction for each question costs about 2 × 10^5 steps. A total can reach 10^11, so it needs a 64-bit integer.