Engineering platform~30 min2s · 256 MBtarget O(n log n) time, O(n) spaceheaps
An online exam portal shows two bars while students submit their papers. One bar is the total marks of the students in the lower half of the scores so far, and the other is the total of the upper half.
Scores arrive one at a time, up to 100,000 of them, each from 0 to 10,000. After every score the portal must update both bars. Sorting everything after each score would be too slow.
Write half_totals(scores).
scores[i] is the i-th score to arrive.m scores have arrived, sort them. The lower half is the first (m + 1) // 2 scores of the sorted list, so the middle score of an odd count belongs to the lower half. The upper half is the rest.m from 1 to n, return [total of the lower half, total of the upper half]. An empty half has total 0.Input: scores = [5, 2, 8, 6, 3]
Output: [[5, 0], [2, 5], [7, 8], [7, 14], [10, 14]]Keep the lower half in a max-heap and the upper half in a min-heap, with a total for each. The lower half always holds the same number of scores as the upper half, or one more.
| Score | Goes to | After rebalancing: lower half | upper half | Totals |
|---|---|---|---|---|
| 5 | lower (it is empty) | 5 | [5, 0] |
|
| 2 | lower (2 ≤ 5), then 5 moves to the upper half | 2 | 5 | [2, 5] |
| 8 | upper (8 > 2), then 5 moves back to the lower half | 2, 5 | 8 | [7, 8] |
| 6 | upper (6 > 5) | 2, 5 | 6, 8 | [7, 14] |
| 3 | lower (3 ≤ 5) | 2, 3, 5 | 6, 8 | [10, 14] |
Input: scores = [7]
Output: [[7, 0]]One score: the lower half holds it, and the upper half is empty.
Input: scores = [4, 4, 4, 4]
Output: [[4, 0], [4, 4], [8, 4], [8, 8]]Equal scores are split by position in the sorted list: after 3 scores the lower half has 2 of them.
1 ≤ length of scores ≤ 10^50 ≤ scores[i] ≤ 10^4Sorting all the scores after each new one costs about n^2 log n steps in all: for 100,000 scores that is more than 10^11. A heap can place one new score in log n steps.
Totals reach 10^4 × 10^5 = 10^9, which still fits an int.