28/42
Part 6 of 8 · The best setLearn and do
For thousands of machines, a table over GPU totals replaces the search
For thousands, stop listing sets and build a table instead. It's a dynamic program like the one in the sorting and binary search lesson's worked example.
best[g] is the least cost of a set of the machines seen so far whose GPUs add up to g. Any total at or above need counts as need. Fill the table one machine at a time, and the answer is best[need]:
import math
def least_cost(machines, need):
# best[g]: least cost for g GPUs, g capped at need
best = [0] + [math.inf] * need
for m in machines.values():
# downward, so each machine is used at most once
for have in range(need, -1, -1):
if best[have] < math.inf:
to = min(need, have + m["gpus"])
best[to] = min(best[to], best[have] + m["cost"])
return best[need]
print(least_cost(MACHINES, 8))
The table keeps the cheapest cost to reach each GPU total. What's the cheapest way to at least 8 GPUs, after every machine?
Pick one to see what it prints.
Pick an answer above to see the rest