2-D Dynamic Programming Knapsack
556. Rod Cutting
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]
42Explanation: 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]
11Explanation: 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]
4000000000Explanation: 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.
Constraints
1 ≤ n = price.length ≤ 30001 ≤ price[i] ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.