Bank app~35 min2s · 256 MBtarget O(n log n) time, O(n) spaceclassic twin: lc-502heaps · greedy · sorting
A bank app offers small-business loans to a lender. Each loan has a minimum balance the lender must hold to take it, and a profit that is added to the balance when the loan is taken. Each loan can be taken once.
The lender can take at most rounds loans, one in each round. Your team lead says: "Show the highest balance the lender can reach." The list can hold 100,000 loans, and a loan that is too expensive now may be affordable after an earlier loan pays out.
Write best_final_balance(profits, minimums, rounds, start).
profits[i] and minimums[i] describe loan i. Both lists have the same length.start. A loan can be taken when the current balance is at least its minimum. Taking it adds its profit to the balance.rounds loans can be taken in total. Fewer is allowed.int.Input: profits = [3, 5, 4, 9, 2], minimums = [2, 6, 5, 9, 1], rounds = 3, start = 3
Output: 20Sort the loans by their minimum. In each round, move every loan the balance now covers into a max-heap of profits, and take the largest profit.
| Round | Loans that become affordable (minimum, profit) | Profit taken | Balance | Profits left in the heap |
|---|---|---|---|---|
| 1 | (1, 2) and (2, 3) | 3 | 6 | 2 |
| 2 | (5, 4) and (6, 5) | 5 | 11 | 4, 2 |
| 3 | (9, 9) | 9 | 20 | 4, 2 |
The highest balance is 20.
Input: profits = [2, 10, 3], minimums = [0, 6, 4], rounds = 3, start = 1
Output: 3Only the first loan is affordable at the start. After it the balance is 3, and the other loans need 6 and 4. The lender stops with 3.
Input: profits = [4], minimums = [9], rounds = 1, start = 5
Output: 5The only loan needs 9, and the balance is 5. No loan is taken.
1 ≤ length of profits = length of minimums ≤ 10^5, and 0 ≤ profits[i], minimums[i] ≤ 10^91 ≤ rounds ≤ 10^5, and 0 ≤ start ≤ 10^9Scanning all loans for the best affordable one in each round costs n steps, and there are up to rounds rounds. For 100,000 of each that is 10^10 steps.
Sorting by minimum costs about 100,000 × 17 steps, and each loan enters the heap once and leaves at most once. The balance can reach 10^14, so it needs a 64-bit integer.