Rod Cutting Problem
A rod of length n can be cut into integer pieces, where a piece of length i sells for price[i-1]. Maximise the total selling value.
Intuition
This is knapsack with unlimited copies: piece lengths can be reused as often as they fit. The trick that collapses the search is to fix only the first piece. Whatever the optimal cutting looks like, it starts with some piece of length f; the rest of the rod is then an independent, already-solved subproblem of length n − f. Trying every f and trusting dp for the remainder covers every possible cutting without ever enumerating them.
Approach
One dimension is enough
dp[L] = best value obtainable from a rod of length L. dp[0] = 0, since a rod of nothing sells for nothing.
Fix the first cut only
dp[L] = max over f in 1..L of price[f-1] + dp[L - f]. The recursion never needs to know which pieces came before.
Sweep upward for reuse
Unlike 0/1 knapsack, dp[L - f] may already include piece f. That is correct here — pieces are unlimited, so the upward sweep is the feature, not a bug.
Solution & live demo
Edge cases
dp[0] = 0; the loop body never executes.
f = L is one of the candidates, so the uncut rod is always considered.
Not applicable — price is indexed 1..n by definition, so every length has a price.