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
INPUTALGORITHMRESULTRod Length = 4Price Array:1589len=1len=2len=3len=4prices[i] = revenue forrod piece of length i+11Build DP table bottom-up2Try all possible first cuts3Choose maximum revenue4Return dp[n] as answerDP Table:15810dp[1]dp[2]dp[3]dp[4]Maximum Revenue10Optimal Strategy:Cut rod into two piecesof length 2 each555 + 5 = 10Key Insight:The optimal way to cut a rod depends on optimal solutions for smaller lengths.Dynamic programming builds up from length 1 to n, reusing computed results.TutorialsPoint - Rod Cutting Problem | Bottom-Up Dynamic Programming
Asked in
Google 35 Amazon 28 Microsoft 22 Facebook 18
34.5K Views
High Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen