Bank app~18 min2s · 256 MBtarget O(k) time, O(1) spacegreedy
You work on a banking app that plans cash machine refills. A machine holds notes of a few values, with a limited number of each. The values are chosen so that every value divides the next larger one, such as 1, 5, 10 and 50.
A customer asks to withdraw an amount in whole units. Your team lead asks: "What is the fewest notes that pay it exactly?" Machines can be refilled with up to a billion notes of each value.
Write fewest_notes(notes, stock, amount).
notes lists the note values from smallest to largest. Every value divides the next one.stock[i] is how many notes of value notes[i] the machine holds.amount exactly, using at most stock[i] notes of each value.-1 when the machine cannot pay the amount exactly.Input: notes = [1, 5, 10, 50], stock = [3, 4, 2, 1], amount = 78
Output: 7Start with the largest note. Take as many as the amount and the stock allow, then move to the next smaller note.
| Note | In stock | Taken | Amount left |
|---|---|---|---|
| 50 | 1 | 1 | 28 |
| 10 | 2 | 2 | 8 |
| 5 | 4 | 1 | 3 |
| 1 | 3 | 3 | 0 |
The amount reaches 0 after 7 notes in total.
Input: notes = [2, 10], stock = [5, 5], amount = 7
Output: -1The values are all even, so an odd amount can never be paid.
Input: notes = [1, 4], stock = [0, 3], amount = 12
Output: 3There are no 1 notes, and three notes of 4 pay exactly 12.
1 ≤ len(notes) = len(stock) ≤ 121 ≤ notes[i] ≤ 1,000,000,000, and each value divides the next larger one0 ≤ stock[i] ≤ 1,000,000,0001 ≤ amount ≤ 1,000,000,000,000A table over every amount up to a trillion cannot fit in memory or finish in time. Trying every count of every note is also far too large when each note has up to a billion in stock. The note values divide each other. With such a set, taking the largest note that fits is always safe, so one pass over at most 12 values is enough.