Ride-hailing app~20 min2s · 256 MBtarget O(n log n + m log m) time, O(1) extra spaceclassic twin: lc-455greedy
A scooter-sharing fleet has scooters that each need a minimum charging power, and charging docks that each supply a fixed power. A dock must supply at least the power that a scooter needs.
A dock must also not supply much more than needed, because strong charging wears the battery. The dock may exceed the need by at most slack. Each dock charges one scooter, and each scooter uses at most one dock.
You find the most scooters that can be charged.
Write most_scooters_charged(needs, docks, slack).
needs[i] is the power that scooter i needs, and docks[j] is the power that dock j supplies.j can charge scooter i when needs[i] <= docks[j] <= needs[i] + slack.Input: needs = [3,5,8,9], docks = [4,5,9,12,13], slack = 2
Output: 3The solution sorts both lists and walks them together. For the weakest scooter and the weakest dock, it skips a dock that is too weak, skips a scooter that the dock overshoots, or makes a match.
| Scooter needs | Dock supplies | What happens |
|---|---|---|
| 3 | 4 | within 3 to 5, match |
| 5 | 5 | within 5 to 7, match |
| 8 | 9 | within 8 to 10, match |
| 9 | 12 | more than 9 + 2, so skip the scooter |
No scooter is left, so 3 scooters are charged.
Input: needs = [3,5,8,9], docks = [4,5,9,12,13], slack = 100
Output: 4With a band of 100, any dock that is strong enough works. The docks 4, 5, 9 and 12 charge the four scooters in order.
Input: needs = [3,5,8,9], docks = [4,5,9,12,13], slack = 0
Output: 2With no slack the dock must supply exactly the need. Only the scooters that need 5 and 9 find such a dock.
1 ≤ len(needs), len(docks) ≤ 100,0000 ≤ slack ≤ 1,000,000Trying every scooter with every dock costs about 10,000,000,000 pairs, and choosing the best set of pairs is harder still. After sorting, one walk over both lists costs about 200,000 steps.