Bank app~30 min2s · 256 MBtarget O(n × S) time, O(S) spaceknapsack
You work on a settlement system of a bank. Pending transfers wait for the next settlement batch. Every transfer has a fee, in units, that the bank must pre-fund, and a priority score from 1 to 50.
The batch can pre-fund at most cap units of fees in total. A transfer is either in the batch or not, and each transfer can be in the batch only once.
Your team lead asks: "What is the largest total priority score that fits under the fee cap?" There are at most 100 transfers, but fees and the cap can reach 1,000,000,000 units.
Write best_batch_score(transfers, cap).
transfers[i] = [fee, score] gives the fee in units and the priority score of transfer i. The score is between 1 and 50.cap.0 when no transfer fits.Input: transfers = [[3, 4], [4, 5], [2, 3]], cap = 6
Output: 8With three transfers there are eight sets. Their fees and scores:
| Set (transfer numbers) | Total fee | Total score | Within the cap? |
|---|---|---|---|
| {} | 0 | 0 | yes |
| {1} | 3 | 4 | yes |
| {2} | 4 | 5 | yes |
| {1, 2} | 7 | 9 | no |
| {3} | 2 | 3 | yes |
| {1, 3} | 5 | 7 | yes |
| {2, 3} | 6 | 8 | yes |
| {1, 2, 3} | 9 | 12 | no |
The best set within the cap of 6 is transfers 2 and 3, with a fee of 6 and a score of 8.
Input: transfers = [[5, 10], [7, 3]], cap = 4
Output: 0Both fees are above the cap, so nothing can be in the batch.
Input: transfers = [[1, 2], [2, 3], [3, 4]], cap = 1000
Output: 9All three fees fit, so the score is 2 + 3 + 4.
1 ≤ len(transfers) ≤ 1001 ≤ transfers[i][0] ≤ 1,000,000,000 (the fee)1 ≤ transfers[i][1] ≤ 50 (the score)0 ≤ cap ≤ 1,000,000,000The usual table has one entry for each possible fee total, up to the cap. For a cap of 1,000,000,000 that is 1,000,000,001 entries, and with 100 transfers it takes 100 billion steps. But the scores are small: at most 100 × 50 = 5,000 in total. A table indexed by score has only 5,001 entries.