Parcel-delivery app~15 min2s · 256 MBtarget O(n log n) time, O(n) spaceclassic twin: lc-462greedy
You work on a delivery network with a row of warehouses. Each warehouse holds some units of one product. A worker can add one unit to a warehouse or remove one unit from it, and each change is one move.
Your team lead asks: "What is the fewest number of moves that gives every warehouse the same stock?" The network has up to 100,000 warehouses.
Write min_moves(stock).
stock[i] is the number of units in warehouse i.Input: stock = [1, 10, 2, 9]
Output: 16Sort the stock: [1, 2, 9, 10]. Take the middle value 9 as the target. Each warehouse needs |stock - target| moves.
| Stock | Target | Moves |
|---|---|---|
| 1 | 9 | 8 |
| 10 | 9 | 1 |
| 2 | 9 | 7 |
| 9 | 9 | 0 |
The moves add up to 16. The value 2 is as good a target, and it also gives 16.
Input: stock = [4, 4, 4]
Output: 0All the warehouses already hold the same stock.
Input: stock = [5, 1]
Output: 4Move one warehouse to the level of the other: 4 moves, to either 1 or 5 or any level between them.
1 ≤ len(stock) ≤ 100,0001 ≤ stock[i] ≤ 1,000,000,000You cannot try every target level: there are up to a billion of them, and each needs a pass over 100,000 warehouses. The target has to come from a rule. The total number of moves can reach 100,000 × 1,000,000,000 = 100,000,000,000,000, so it needs a 64-bit type.