Ad platform~20 min2s · 256 MBtarget O(m log n) time, O(1) spacecomplexity
An ad platform sorts its impression events every night, in batches. A sort works in passes. It halves its pieces until each piece holds one event, and each pass touches every event of the batch once, at one step for each event.
The team wants to know how long a night's sorting takes. The machine does a fixed number of steps in each millisecond. You will add the steps of all batches and turn them into time.
Write sort_time_ms(batches, steps_per_ms).
batches[i] is the number of events in batch i. A batch of n events needs p passes, where p is the smallest whole number with 2^p >= n. A batch of 0 or 1 events needs 0 passes.n steps, so the batch costs n * p steps.steps_per_ms steps in each millisecond.steps_per_ms, rounded up to a whole number of milliseconds.Input: batches = [1, 2, 3, 4], steps_per_ms = 5
Output: 4Each batch costs n steps for each pass, and the passes are the smallest p with 2 to the p at least n. The rate is 5 steps a millisecond.
| Batch size n | Passes | Steps | Running total |
|---|---|---|---|
| 1 | 0 | 0 | 0 |
| 2 | 1 | 2 | 2 |
| 3 | 2 | 6 | 8 |
| 4 | 2 | 8 | 16 |
The total is 16 steps. Divided by 5 and rounded up, that is 4 milliseconds.
Input: batches = [5000000], steps_per_ms = 100000
Output: 1150A batch of 5,000,000 events needs 23 passes, because 2 to the 22 is 4,194,304 and 2 to the 23 is 8,388,608. That is 115,000,000 steps. At 100,000 steps a millisecond the sort needs 1150 milliseconds.
Input: batches = [0], steps_per_ms = 7
Output: 0An empty batch costs no steps, so the time is 0.
1 ≤ batches.length ≤ 100,000 (batches)0 ≤ batches[i] ≤ 5,000,000 (events in a batch)1 ≤ steps_per_ms ≤ 1,000,000 (steps in one millisecond)Running every pass of every batch makes more than 10^13 steps at the top size, which is far too many. A batch costs n * p steps, and p is at most 23, so one short loop for each batch is enough. The total needs a 64-bit integer.