oneby7

2-D Dynamic Programming Knapsack

556. Rod Cutting

Hard

You have a rod of length n and a price list with n entries. A piece of length i + 1 sells for price[i], so price[0] is the price of a piece of length 1 and price[n − 1] is the price of the whole rod.

You may cut the rod into pieces of whole lengths, as many as you like, or sell it in one piece. Several pieces may have the same length. Cutting is free.

Return the most money you can get by selling every piece.

Example 1

Input: price = [3, 12, 21, 28, 36, 37]

Output: 42

Explanation: Cut the rod into two pieces of length 3 and sell each for 21. A piece of length 5 and a piece of length 1 bring only 36 + 3 = 39, and lengths 2 and 4 bring 12 + 28 = 40.

Example 2

Input: price = [2, 5, 6, 11]

Output: 11

Explanation: Sell the rod whole for 11. The best set of cuts, two pieces of length 2, brings only 10.

Example 3

Input: price = [1000000000, 1000000000, 1000000000, 1000000000]

Output: 4000000000

Explanation: Every length sells for 109, so we cut four pieces of length 1.

Check your understanding

Work out the answer for this input before you write any code.

price = [3, 5, 14, 19, 20, 23]

Constraints

  • 1 ≤ n = price.length ≤ 3000
  • 1 ≤ price[i] ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.