All topics
123

A whole subset packed into one number

Tier 1Locked

Where it runs

1. The problem

A build farm (a group of servers that build code) has n machines and n jobs. Each machine runs each job at its own speed, so cost[i][t] is the estimated minutes for machine i to run job t. You want to hand out the jobs so every machine gets exactly one and the total minutes are as low as possible.

Trying every arrangement means n! options, and n! grows very fast: at n = 12 it is already 479,001,600. The greedy shortcut fails too: "each machine in turn takes the fastest free job". Take cost = [[1, 2], [1, 9]]. Machine 0 takes job 0 for 1 minute, machine 1 is left with job 1 for 9 minutes, total 10. If machine 0 takes job 1 instead (2 minutes), machine 1 takes job 0 (1 minute), total 3. The cheap early pick forced an expensive late one.

What saves you is that n is small here: machines in a rack, maybe a dozen. When there are few elements, you can store the answer to "which jobs are already taken" compactly.

This step is part of the paid track

The first 33 steps are open to everyone: lesson, exercise and tests. This one opens with full access. Start with a free account and the free steps.

Create a free accountSee what is included

Recognise it

Dynamic programming (1-D)

Say these words and it is this pattern

  • best/maximum/minimum ending at position i
  • ways to reach, climb, or tile
  • cannot pick two adjacent items
  • minimum cost path through a grid
  • overlapping subproblems, same state recomputed

Looks similar, isn't

n states with O(1) work each gives O(n). Memory drops to O(1) when only the last states matter.

On LeetCode

Assignment and visiting problems on up to about 15 items, where the state is which items are already used. dp[mask] stores the best answer for that set, and the number of 1 bits in mask says whose turn is next.

We use necessary cookies to run the site (sign-in and language). If you accept, we also load Google Analytics to see which pages are used, and Google reCAPTCHA to keep spam off the contact and bug-report forms. Privacy policy