What is Rod Cutting
A rod of length n may be cut into integer pieces. price[i] is the price of a piece of length i+1. The best profit for length L tries every first cut i and adds the already-solved remainder dp[L-i].
Brute force approach
i and recurse on n-i. The same remainder is recut from many parents — exponential.A rod of length L tries every first-cut length, then solves the leftover length. The same leftover is priced many times. Memoization stores one best price per length.
At most 4 prices, for lengths 1, 2, 3, and 4. Prices 1 5 8 9 give 10.
Memoized approach
dp[L] = max(price[i-1] + dp[L-i]). Each length is locked once. Time O(n^2).Each state is solved once. A dashed node is a cache hit: the call returns immediately and that branch stops.
1, 5, 8, 9 (n=4). Watch every first-cut for each length. The best for 4 is 10 (two 2s). Step through the DP table. The live code on the right is the DP recurrence — brute force is shown in Implementations below so you can see why it TLE.Interactive DP trace
Pseudocode & Complexity
| Operation | Time |
|---|---|
| Each (L, cut) | O(1) |
| All lengths | O(n²) |
| Space | O(n) |
Brute force explores the same subproblems many times and will TLE on the hidden tests. The DP codes below reuse each answer once.
Implementations