Rod Cutting Problem - Problem
You are given a rod of length N and an array of prices where prices[i] represents the price you can get for selling a rod piece of length i+1.
Your task is to determine the maximum revenue you can obtain by cutting the rod into pieces and selling them. You can make any number of cuts, and each piece must have an integer length.
Example: If the rod has length 4 and prices = [1, 5, 8, 9], you can:
- Sell as one piece of length 4: revenue = 9
- Cut into pieces of length 1+3: revenue = 1 + 8 = 9
- Cut into pieces of length 2+2: revenue = 5 + 5 = 10
- Cut into pieces of length 1+1+2: revenue = 1 + 1 + 5 = 7
- Cut into pieces of length 1+1+1+1: revenue = 1 + 1 + 1 + 1 = 4
The maximum revenue is 10.
Input & Output
Example 1 — Basic Rod Cutting
$
Input:
prices = [1,5,8,9], n = 4
›
Output:
10
💡 Note:
Cut rod into two pieces of length 2 each. Revenue = prices[1] + prices[1] = 5 + 5 = 10. This is better than keeping it whole (9) or other combinations.
Example 2 — Keep Whole Rod
$
Input:
prices = [1,5,8,20], n = 4
›
Output:
20
💡 Note:
Best strategy is to keep the rod whole and sell for prices[3] = 20. Any cuts would result in lower revenue.
Example 3 — All Unit Cuts
$
Input:
prices = [3,1,1,1], n = 4
›
Output:
12
💡 Note:
Cut into 4 pieces of length 1 each. Revenue = 3 + 3 + 3 + 3 = 12. Unit pieces give highest price per unit length.
Constraints
- 1 ≤ n ≤ 1000
- 1 ≤ prices.length ≤ n
- 1 ≤ prices[i] ≤ 1000
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code