Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Dynamic Programming

0/1 Knapsack

O(n · W)

dp over (item, capacity) choosing include vs exclude; iterate capacity backward for the 1D rolling version.

  1. 1Learnthe lesson(you are here)
  2. 2Guidedwatch it run, line by line(not yet)
  3. 3Practisethe path, or the climb(not yet)
  4. 4Revisereviews on schedule(not yet)
Start the lesson
Learn first1D / Fibonacci-styleUnlocksUnbounded KnapsackBitset Optimisation
0%
mastery
0/19 solved
IdeaPracticeTemplatePitfalls

Recognise it

The signal

Each item take-or-skip under a capacity; can a subset hit exact target T; partition into equal halves; +/- target sum.

  1. 1Brute force

    Enumerate all 2n subsets.

  2. 2The observation

    Exponential subsets: only the reachable (index, capacity) pairs matter.

  3. 3Why it works

    After item i, dp[w] is the best result using a subset of items 1..i with capacity w.

Reach for it when

  • +Each item is used at most once, under a capacity/budget — maximise value or hit an exact target.
  • +'Can a subset sum to T?', 'partition into equal halves', 'closest achievable sum'.
  • +Capacity W is small enough that O(n·W) is affordable.

Not when

  • ×Items can be reused unlimited timesuse Unbounded knapsack (capacity loop forward)
  • ×W is huge (e.g. 1e9) but n <= ~40use Meet in the middle
  • ×n <= 20 with complex constraints between itemsuse Bitmask DP
  • ×Items are fractionaluse Greedy by value/weight
  • ×Order of picking matters / it's sequence alignmentuse A different DP over sequences

Intuition

0/1 knapsack is the "each item: take it or leave it, once" pattern. You have a backpack with a weight limit and items each with a weight (and maybe a value); maximise value, or just answer "can I exactly fill capacity W?".

Read the full intuition

The state has two dimensions now: which items you've considered and how much capacity is left. dp[i][w] = best you can do using the first i items with capacity w. For each item you face one decision:

  • Skip it: dp[i-1][w] (same capacity, one fewer item).
  • Take it (if it fits): value[i] + dp[i-1][w - weight[i]]. Take the better. That's the entire pattern.

The famous space trick: dp[i] only depends on row i-1, so you can keep one 1-D array and update it. But you must loop capacity backwards (W down to weight[i]). Why backwards? Going forward, you'd read dp[w - weight] after already updating it this round — that would let you use the same item twice. Backwards keeps each update reading the previous row's value, enforcing "use each item at most once."

Walk Partition Equal Subset Sum: can a subset sum to total/2? That's "can these item-weights exactly fill capacity = total/2?" — a boolean knapsack. dp[w] = "is sum w reachable?"; seed dp[0]=True; for each number, for w from target down to num: dp[w] |= dp[w-num].

Key idea

The mental translation that unlocks half of DP: "pick a subset hitting a target" ≡ 0/1 knapsack with capacity = target.

Why it costs what it costs

Time O(n·W). n items × W capacities, each updated in O(1).

Space O(W). the 2-D table collapses to one row since dp[i] reads only dp[i-1].

Practice

Next · Foundation

Book Shop

dp[w] with w descending so each item is used once.

0/19 solved
  • Book ShopFoundationFoundationCSESMedium
  • Partition Equal Subset SumApply it · Boolean subset sum to total/2.Apply itMedium
  • Ones and ZeroesOne change · Two capacity dimensions.One changeMedium
  • Target SumTwists · Signs instead of choose/skip.TwistsMedium
  • Last Stone Weight IIBranches · Disguised partition.BranchesMedium
  • Money SumsBranches · All reachable sums.BranchesCSESMedium
  • Two Sets IICombine · Count partitions mod p.CombineCSESMedium
  • Profitable SchemesMastery checkMastery checkHard
  • Subsets with Fixed AverageCSESHard
  • School ExcursionCSESMedium
  • Book Shop IICSESMedium
  • Complete the Projects (hard version)Codeforces2300

Pitfalls

Classic bugs

  • !1-D capacity loop going forward reuses items (that's unbounded). Loop backward.
  • !Backward range must reach num inclusive: range(target, num-1, -1).
  • !Forgetting the seed dp[0] = True / 0 (empty subset): the whole recurrence builds from it.
  • !Target Sum: count subsets summing to (total + S) / 2; first check it's a non-negative integer.
  • !Partition Equal Subset Sum: odd total means instantly false.

Looks like it, isn't

  • Partition to K Equal Sum Subsets needs Bitmask DP
    Why
    k buckets cannot be tracked by a single capacity; use bitmask DP or pruned backtracking.
  • Count of Sub-Multisets With Bounded Sum needs Bounded (Multiple) Knapsack
    Why
    Expanding every copy is O(n*S). Grouping equal values and using residue-class window sums makes it O(sqrt(S) * S). source ↗
Go deepervariants and techniques · 5 combinations · resources

Variants and techniques

  • Bounded (Multiple) KnapsackInterview · hardEach item type can be taken up to c_i times. Split each count into powers of two, for O(W * sum log c_i). Or, for each residue mod w_i, run a sliding-window max or sum along that residue class, for O(nW).
  • Boolean subset-sumdp[w] |= dp[w-num]; ask dp[target]. Partition Equal Subset Sum.
  • Count subsets to targetdp[w] += dp[w-num] (integer counts). Target Sum (after transform).
  • Two capacitiesdp[i][j] over two budgets (zeros and ones). Ones and Zeroes — loop both backward.
  • Minimize differenceFind the achievable subset sum closest to total/2, answer = total - 2·bestSum. Last Stone Weight II.

Combinations

  • Bounded (Multiple) Knapsack+Prefix Sum

    count multisets/ways with per-type limits and a bounded sum

    Bounded (Multiple) Knapsack:
    group equal values with their counts
    Prefix Sum:
    window sums along each residue class give dp_new[s] = sum of dp[s - j*v] for j <= c

    Count of Sub-Multisets With Bounded SumNumber of Ways to Earn Points

  • Bounded (Multiple) Knapsack+Monotonic Deque

    maximise value with up to c_i copies of item i, W ~ 1e5

    Bounded (Multiple) Knapsack:
    item counts c_i
    Monotonic Deque:
    sliding-window max of dp[r + j*w] - j*v over the last c_i positions of each residue

    Book Shop II

  • Exchange-Argument Sorting (custom comparator)+0/1 Knapsack

    choose and order projects/rewards with requirement and change values to maximise the count/total

    Exchange-Argument Sorting (custom comparator):
    fixes the processing order (gains first; losses by a_i + b_i descending)
    0/1 Knapsack:
    picks the subset to take, in that order

    Complete the Projects (hard version)Maximum Total Reward Using Operations I

  • Bitset Optimisation+0/1 Knapsack

    which totals are reachable, values up to 5e4, n up to 5e4

    Bitset Optimisation:
    a shift-or over word-packed bits
    0/1 Knapsack:
    boolean reachability of sums

    Maximum Total Reward Using Operations II

  • Union-Find (Disjoint Set)+Bitset Optimisation+0/1 Knapsack

    split the vertices into two groups without breaking components, for every possible size

    Union-Find (Disjoint Set):
    component sizes
    Bitset Optimisation:
    makes the subset sum fast
    0/1 Knapsack:
    which totals of component sizes are achievable

    School Excursion

Resources

  • DP lecture notesErrichto · video
  • AtCoder Educational DP ContestAtCoder · sheet
  • Introduction to DPUSACO Guide · course
  • Dynamic Programming PatternsLeetCode discuss · article
  • Dynamic Programming playlistAditya Verma · video
  • Bitmask DPUSACO Guide · course
  • Digit DPCodeforces · blog
1D / Fibonacci-styleUnbounded Knapsack
TodayReviewPatternsProblems

Template · clean C++, Java and Python to revise from

Start the free 7-day trial