Social feed~30 min2s · 256 MBtarget O(n log n) time, O(n) spaceclassic twin: lc-493sorting
A social app gives each post an engagement score, measured against the feed's average, so a score can be negative. The ranking team wants to know how often an early post scored far above a later one. Call a pair of posts a sharp drop when the earlier post scored more than double the later one.
The posts are in the order they were published. You count the sharp drops over the whole list, as a measure of how fast attention fades.
Write count_sharp_drops(scores).
scores[i] is the score of the i-th post, in publishing order. Scores can repeat, and they can be negative.i < j with scores[i] > 2 * scores[j].Input: scores = [8, 3, 5, 1]
Output: 4The sharp drops are (8, 3), (8, 1), (3, 1) and (5, 1). Split the list into [8, 3] and [5, 1]. Each half holds one drop. Sort the halves into [3, 8] and [1, 5], and count the drops across them.
| Left value | Right values with 2 × value below it | Added | Total across |
|---|---|---|---|
| 3 | [1] | 1 | 1 |
| 8 | [1] | 1 | 2 |
The total is 1 + 1 + 2 = 4.
Input: scores = [4, 4, 4]
Output: 0Equal scores are never a sharp drop.
Input: scores = [5, 2, 2, 1]
Output: 3The drops are (5, 2), (5, 2) and (5, 1). The pair (2, 1) is not a drop, because 2 is not more than double 1.
0 ≤ scores.length ≤ 100,000 (posts)−1,000,000,000 ≤ scores[i] ≤ 1,000,000,000Checking every pair costs about n × n / 2, which is 5 × 10^9 at n = 100,000. Merge sort costs about n log n, roughly 1.7 million steps for each of two passes. The count can pass 2,147,483,647, so use a 64-bit integer.