Engineering platform~20 min2s · 256 MBtarget O(n log n + q) time, O(n) spacesorting
You work on a dashboard that shows one row of slots. You have a list of numbers to place in the slots, one number in each slot, in any order you like. Many panels then read the row, and each panel adds up a range of neighbouring slots.
Your team lead asks: "In which order should the numbers go, so that the panels show the largest total?" The row can have 100,000 slots and 100,000 panels.
Write best_total_of_reads(values, queries).
values holds the numbers to place. You may put them into the slots in any order.queries[k] = [l, r] is a panel that adds up the slots from position l to position r, both included. Positions start at 0, and 0 ≤ l ≤ r < len(values).Input: values = [3, 5, 1], queries = [[0, 1], [1, 2]]
Output: 14Count how many panels read each slot: slot 0 is read by 1 panel, slot 1 by 2 panels, slot 2 by 1 panel. Put the biggest number in the most-read slot.
| Slot | Panels reading it | Number placed |
|---|---|---|
| 0 | 1 | 1 |
| 1 | 2 | 5 |
| 2 | 1 | 3 |
The total is 1 × 1 + 2 × 5 + 1 × 3 = 14. Another order with the 5 in slot 1 gives the same.
Input: values = [4], queries = [[0, 0]]
Output: 4One slot, read once.
Input: values = [2, 9, 2, 9], queries = [[0, 3]]
Output: 22One panel reads every slot once, so every order gives the same total.
1 ≤ len(values) ≤ 100,000 and 1 ≤ values[i] ≤ 100,0001 ≤ len(queries) ≤ 100,000, and 0 ≤ l ≤ r < len(values)Trying every order is impossible: 100,000 numbers have more orders than any computer can list. Even adding up each panel one slot at a time costs up to 100,000 × 100,000 = 10,000,000,000 steps. You need a rule for the order, and a faster way to count the reads.