Technique · Interview · hard
Bounded (Multiple) Knapsack
Each 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).
0/3 solved
Recognise it
The signal
item i can be taken up to c_i times
1Brute force
Expand every copy into its own 0/1 item: O(W * sum c_i).
2The observation
Copies of the same item are interchangeable, so unrolling them repeats identical transitions.
3Why it works
dp_new[w] depends only on dp_old at w, w - w_i, ..., w - c_i*w_i, which is a window of c_i+1 positions in one residue class.
Reach for it when
- +count sub-multisets with sum in [l, r]
- +values repeat a lot and the total sum is bounded
Not when
- ×every count is 1 (plain 0/1)
- ×counts are unlimited (dp-unbounded)
Practice
Pitfalls
Misconceptions
- !binary splitting needs the remainder piece c - (2k - 1)
- !zero-weight items (LC 2902 has zeros) multiply the answer by (c0 + 1)
Go deeper2 combinations · resources
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