Payments app~25 min2s · 256 MBtarget O((n + m) log (n + m)) time, O(n + m) spaceclassic twin: lc-452greedy
A payments system settles transactions in batch runs. Each transaction can be settled only in its window, from an opening minute to a closing minute, and both ends count. A batch run at minute t settles every transaction whose window contains t.
Batch runs can only start at certain minutes, because the bank connection is open then. The team wants every transaction settled with as few batch runs as possible.
Write fewest_batch_runs(windows, runs).
windows[i] is [open, close] with open <= close: the minutes in which transaction i can be settled, both ends included.runs lists the minutes at which a batch run may start. A minute can appear once or more.t settles every transaction with open <= t <= close.-1 if some transaction has no allowed run minute in its window.Input: windows = [[1,5],[2,8],[7,12],[10,14],[13,16]], runs = [3,6,9,12,15]
Output: 3The solution sorts the windows by closing minute. For a window that no earlier run settles, it chooses the latest allowed run minute that is not after the window closes.
| Window | Already settled by the last run | Run chosen | Runs so far |
|---|---|---|---|
[1,5] |
no run yet | latest allowed minute up to 5 is 3 | 1 |
[2,8] |
yes, 3 is inside | none | 1 |
[7,12] |
no, 7 is after 3 | latest allowed minute up to 12 is 12 | 2 |
[10,14] |
yes, 12 is inside | none | 2 |
[13,16] |
no, 13 is after 12 | latest allowed minute up to 16 is 15 | 3 |
Three runs are enough, so the answer is 3.
Input: windows = [[1,5],[2,8],[7,12],[10,14],[13,16]], runs = [3,6,9,15]
Output: -1The window [10,14] has no allowed run minute inside it, because 9 is too early and 15 is too late. That transaction can never be settled, so the answer is -1.
Input: windows = [[2,4],[3,5],[4,6]], runs = [4]
Output: 1Minute 4 lies in all three windows, so one run settles all three transactions.
1 ≤ len(windows) ≤ 100,000, and every window is [open, close] with 0 ≤ open ≤ close ≤ 1,000,000,0001 ≤ len(runs) ≤ 100,000, and every run minute is between 0 and 1,000,000,000Trying every set of run minutes costs 2 to the power of 100,000. Checking each window against each run minute costs about 10,000,000,000 pairs. After sorting, each window needs one binary search of about 17 steps, so the whole plan costs about 1,700,000 steps.