Menu
CoddyTech

Rod Cutting Problem

You have a rod of length n, where n = prices.length. A piece of length k sells for prices[k-1]. You may cut the rod into pieces of whole lengths, as many as you like, or sell it in one piece. Return the most money you can earn by selling all of it.

Function

cutRod(prices: integer-array) → integer
pricesinteger-array
prices[k-1] is the price of a piece of length k; the rod is prices.length long
Returnsinteger
the most money the whole rod can earn

Constraints

  • 1 ≤ prices.length ≤ 1000
  • 1 ≤ prices[i] ≤ 105

Examples

Input
prices = [2, 5, 7, 8]
Output
10
Explanation
Two pieces of length 2 sell for 5 + 5 = 10. Selling the rod whole earns 8, and a piece of 1 plus a piece of 3 earns 2 + 7 = 9.
challenge icon

Follow-up

What if you may cut the rod at most m times? What does each table entry need to know then?

Reset code
def cutRod(prices):
    # Write code here

Test #1

Test #2

Test #3

Argument

prices = [2, 5, 7, 8]

Expected Output

10