Music streaming app~25 min2s · 256 MBtarget O(n log n) time, O(n) spacedivide-and-conquer · sorting
You work on a music streaming service. A playlist should rise in popularity, so each track should have a score that is at least that of the tracks before it. A curator tool measures how far a playlist is from that.
A pair of tracks is out of order when the earlier track has the higher score. The disorder of that pair is the score gap. Your team lead asks: "What is the total disorder over all pairs?" A playlist can have 100,000 tracks.
Write total_disorder(scores).
scores[i] is the popularity score of the track at position i.(i, j) with i < j is out of order when scores[i] > scores[j]. Its disorder is scores[i] - scores[j].0 for a playlist that is already in order.Input: scores = [5, 2, 8, 3, 1]
Output: 24List every pair in which the earlier score is larger, and add the gaps. This list is for understanding. The solution never builds it.
| Out-of-order pair | Positions | Gap |
|---|---|---|
| (5, 2) | 0 and 1 | 3 |
| (5, 3) | 0 and 3 | 2 |
| (5, 1) | 0 and 4 | 4 |
| (2, 1) | 1 and 4 | 1 |
| (8, 3) | 2 and 3 | 5 |
| (8, 1) | 2 and 4 | 7 |
| (3, 1) | 3 and 4 | 2 |
The gaps add up to 24.
Input: scores = [1, 2, 3, 4]
Output: 0A playlist that rises has no out-of-order pair.
Input: scores = [9, 9, 4]
Output: 10The two equal scores do not count. Each 9 forms a pair with the 4, with a gap of 5 each.
1 ≤ len(scores) ≤ 100,0000 ≤ scores[i] ≤ 1,000,000A playlist of 100,000 tracks has almost 5 billion pairs, so checking each pair is too slow for a 2-second limit. A merge sort handles 100,000 values in about 1.7 million steps. If the merge can add up a whole group of out-of-order pairs in one step, the same running time gives the answer.