Rod Cutting
Solve this ProblemTest Case 1:
Test Case 2:
Test Case 3:
Constraints
- ◆
1 ≤ prices.length ≤ 20 - ◆
0 ≤ prices[i] ≤ 1000
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
Approach & Solutions
Brute Force — Recursive Without Memoization
BruteA rod of a given length can be sold whole, or cut into a first piece of any length from 1 up to the rod's own length, sold at that piece's price, with the rest of the rod — now shorter — facing the exact same decision all over again. Since it's not obvious in advance which first cut leads to the best total revenue, every possible first-cut length is tried, each paired with the best revenue achievable from whatever length remains afterward, and the largest total across every choice is kept. A rod of length 0 contributes nothing and ends the recursion.
O(2^n)O(n)1class Solution {
2 private int[] prices;
3
4 public int rodCutting(int[] prices) {
5 this.prices = prices;
6 return solve(prices.length);
7 }
8
9 private int solve(int len) {
10 if (len == 0) return 0;
11 int best = 0;
12 for (int L = 1; L <= len; L++) {
13 best = Math.max(best, prices[L - 1] + solve(len - L));
14 }
15 return best;
16 }
17}Optimal — Bottom-Up 1D DP
OptimalTrack, for every rod length from 0 up to the full length, the best revenue achievable by cutting it up. A length-0 rod is worth nothing, and every later length's best revenue comes from trying every possible first-cut length up to it and adding that piece's price to the best revenue already worked out for whatever length remains — since shorter lengths are always filled in before a longer one needs them, that smaller answer is already sitting in the table. The largest total across every first-cut choice becomes that length's entry, and the entry at the full rod length holds the final answer.
O(n²)O(n)1class Solution {
2 public int rodCutting(int[] prices) {
3 int n = prices.length;
4 int[] dp = new int[n + 1];
5 for (int len = 1; len <= n; len++) {
6 for (int L = 1; L <= len; L++) {
7 dp[len] = Math.max(dp[len], prices[L - 1] + dp[len - L]);
8 }
9 }
10 return dp[n];
11 }
12}