Dynamic Programming21 sections · 916 units
Open in Course

Book Shop - Implementation

Apply 0/1 knapsack

Initialize dp[0..x]dp[0..x] = 0. For each book (price, pages), update dp[j]dp[j] = max(dp[j]dp[j], dp[jprice]dp[j-price] + pages) for jj from xx down to price. The reverse iteration is key. If you go forward, you might count the same book multiple times (that's unbounded knapsack, not 0/1). Answer is dp[x]dp[x]. Time: O(n×x)O(n \times x), Space: O(x)O(x). The code directly follows the recurrence relation. Trace through a small example by hand to see how each value is computed.

Time complexity: O(nX)O(n \cdot X).

Space complexity: O(X)O(X).