Dynamic Programming21 sections · 916 units
Open in Course

Bounded Knapsack - Binary Representation

The trick

Instead of treating 7 copies as 7 separate items, represent 7 in binary: 7=1+2+47 = 1 + 2 + 4. Create three "bundle" items with weights w,2w,4ww, 2w, 4w and values v,2v,4vv, 2v, 4v. Any quantity from 0 to 7 can be formed by including/excluding these bundles. Want 5 copies? Take the bundles for 1 and 4. Want 3? Take 1 and 2. This reduces kk items to log2(k+1)\lceil \log_2(k+1) \rceil items. Now run standard 0/1 knapsack. Total time: O(n×W×logk)O(n \times W \times \log k).

Time complexity: O(n×W×logk)O(n \times W \times \log k).

Space complexity: O(W)O(W) for the dp array.