Payments app~20 min2s · 256 MBtarget O((n + d) log n) time, O(n) spaceclassic twin: lc-2558greedy · heaps
A payments app runs cashback pools. Each pool holds some units that the app can pay out to customers. Each day the finance team chooses one pool and pays out most of it, keeping only the whole part of the square root of its size. A pool of 40 units pays out 34 units and keeps 6.
Your team lead says: "After days days, we want as few units left in the pools as possible." There can be 100,000 pools and 100,000 days, so the team cannot try the pools one by one.
Write fewest_units_left(pools, days).
pools[i] is the number of units in pool i.days days pass. A pool of 1 unit keeps 1 unit.days days. It can pass the range of an int.Input: pools = [26, 9, 101, 40, 4], days = 3
Output: 34Keep the pools in a max-heap. Each day, take the largest pool and put back its square root.
| Day | Largest pool | Paid out | Pool afterwards | Pools after the day |
|---|---|---|---|---|
| 1 | 101 | 91 | 10 | 26, 9, 10, 40, 4 |
| 2 | 40 | 34 | 6 | 26, 9, 10, 6, 4 |
| 3 | 26 | 21 | 5 | 5, 9, 10, 6, 4 |
The units left are 5 + 9 + 10 + 6 + 4 = 34.
Input: pools = [100, 1], days = 3
Output: 2The pool of 100 is the largest on every day: it keeps 10, then 3, then 1. The pools hold 1 and 1.
Input: pools = [4, 4, 4], days = 2
Output: 8Two of the three pools keep 2 units each, and the third keeps 4. The total is 8, whichever pools are chosen.
1 ≤ length of pools ≤ 10^5, and 1 ≤ pools[i] ≤ 10^91 ≤ days ≤ 10^5Scanning all pools for the largest one each day costs n steps, and there are d days. For n = d = 100,000 that is 10^10 steps.
A max-heap gives the largest pool in one step and takes it back in log n steps. The pools add up to 10^14 at the start and about 3.2 × 10^9 at the end, so the total needs a 64-bit integer.