758. Cover an exact GPU count with the fewest machines
A cloud offers machine types with fixed GPU counts, for example 1, 4 and 8 GPUs. A job needs an exact number of GPUs, and every extra machine adds setup time, so you want the fewest machines whose GPU counts add up exactly to what the job needs. You may use any machine type as many times as you like.
Write min_machines(sizes, need). sizes is a list of distinct positive integers and need is a non-negative integer. Return the fewest machines that sum exactly to need, or -1 if no combination works. need = 0 takes 0 machines.
def min_machines(sizes, need)Example 1
Input: min_machines([1, 4, 8], 12)
Output: 2 (8 + 4)
Example 2
Input: min_machines([4, 8], 6)
Output: -1
Constraints
- 1 <=
len(sizes)<= 50 - 0 <= need <= 100,000
Hint 1
Start from best[0] = 0.
Hint 2
Use infinity for values you have not reached yet.
Hint 3
Loop over targets outside and sizes inside.
Common mistakes
- Using a greedy pick of the largest size.
- Returning infinity instead of -1.
- Treating need = 0 as impossible.
Understand the idea
This is the classic minimum coin change problem in a cloud setting. A one-dimensional DP table builds answers for small targets first and reuses them for larger ones. For sizes [1, 3, 4]: best[3] = 1, best[4] = 1, best[6] = min(best[5] + 1, best[3] + 1, best[2] + 1) = 2. The table costs O(need x len(sizes)) time. In an interview, a common follow-up is what changes in production: very large targets, a cost per machine type instead of a count, or limited stock of each type.