Social feed~25 min2s · 256 MBtarget O(n log n) time, O(n) spacegreedy
You work on a social feed's moderation tool. Reports about posts wait for one moderator, who handles them one at a time. Each report takes a known number of minutes, and has an urgency weight.
The moderator wants the least total of urgency times waiting time, where a report waits until it is finished. Your team lead asks: "In which order should the reports be handled?" There can be 50,000 reports.
Write least_weighted_wait(minutes, weights).
minutes[i] is how long report i takes, and weights[i] is its urgency.i finishes at time f, it adds weights[i] × f to the total.Input: minutes = [3, 1, 2, 4], weights = [2, 4, 1, 6]
Output: 60Sort the reports by minutes divided by weight, the smallest first. Then add up weight times finishing time in that order.
| Order | Minutes | Weight | Finishes at | Weight times finish |
|---|---|---|---|---|
| report 1 | 1 | 4 | 1 | 4 |
| report 3 | 4 | 6 | 5 | 30 |
| report 0 | 3 | 2 | 8 | 16 |
| report 2 | 2 | 1 | 10 | 10 |
The total is 60. No other order gives less.
Input: minutes = [5], weights = [7]
Output: 35One report finishes at 5, so the total is 7 × 5 = 35.
Input: minutes = [2, 2, 2], weights = [1, 1, 1]
Output: 12Equal reports finish at 2, 4 and 6, so the total is 12 in any order.
1 ≤ len(minutes) = len(weights) ≤ 50,0001 ≤ minutes[i] ≤ 1,0001 ≤ weights[i] ≤ 1,000Trying every order means 50,000 factorial orders, which is beyond any computer. A sort costs about 780,000 steps. So there must be a rule that tells, for any two reports, which should go first, and the rule must work for the whole list at once.