Overview
This is the classic Unbounded Knapsack problem. You have a "knapsack" (rod) of capacity `n`, and you want to fill it with "items" (cuts) that have weight (length) and value (price).
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Given a rod of length n and an array of prices for all pieces of size smaller than n, find the maximum value obtained by cutting up the rod and selling the pieces.
This is the classic Unbounded Knapsack problem. You have a "knapsack" (rod) of capacity `n`, and you want to fill it with "items" (cuts) that have weight (length) and value (price).
Because you can cut multiple pieces of the same length (e.g., cut a rod of length 4 into four pieces of length 1), we iterate the inner loop from LEFT to RIGHT.
`dp[j]` represents the max profit for a rod of length `j`. To update it, we see if making a cut of `len` improves it: `dp[j - len] + price[len]`.
Because we only need the answers from the current row and the left side of the current row, a single 1D array perfectly captures the state transitions.