All topics
114

Picking the best set of things that fit a budget

Tier 1Locked

Where it runs

1. The problem

You run an ad campaign with a fixed budget, say 5,000. In front of you is a list of ad slots. Each one has a price and an expected benefit, its value. You buy a slot whole or not at all; you can't buy half a slot.

Which set of slots gives the most value without going over the budget? The first idea is to try every possible set. With 10 slots there are 1024 sets, which is fine. With 40 there are more than a trillion, and the search runs for hours.

This is the 0/1 knapsack problem, one of the DP shapes you meet most often in real work. "0/1" means each item is either taken whole (1) or left out (0).

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

Problems where each item is taken once or left, under a limit, such as splitting an array into two equal sums or reaching a target with plus and minus signs. The table is indexed by item and remaining capacity.

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