Dynamic Programming21 sections · 916 units
Open in Course

Book Shop - Walkthrough

Applying the pattern

Book Shop has nn books with prices pip_i and page counts sis_i. You have budget xx. get the highest total pages. This is 0/1 Knapsack: price is weight, pages are value, budget is capacity.

Each book can be bought at most once. Let dp[i][b]dp[i][b] = max pages from books 1..i1..i with budget bb. Transition: dp[i][b]=max(dp[i1][b],dp[i1][bpi]+si)dp[i][b] = \max(dp[i-1][b], dp[i-1][b-p_i] + s_i) if bpib \geq p_i. space reduction: since we only look at the previous row, we can use 1D array and iterate budget in reverse. This is the standard 0/1 Knapsack trick.