Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Dynamic programming

Cut a rod for the most money

Medium · Target 15 minutes · Dynamic programming

A piece of rod of length L (1 ≤ L ≤ prices.length) sells for prices[L − 1]. Given a rod of length n, cut it into pieces whose lengths each appear in the price list and return the largest total revenue. Pieces may have equal lengths, and the whole rod may be sold as one piece if its length is listed.

Examples

InputOutputWhy
prices = [1,5,8,9,10,17,17,20], n = 8222 + 6: 5 + 17.
prices = [3,5,8,9,10,17,17,20], n = 824Eight pieces of length 1.
prices = [2], n = 510Only length 1 can be sold.

Constraints

  • 1 ≤ prices.length ≤ 1000
  • 0 ≤ n ≤ 1000
  • 1 ≤ prices[i] ≤ 10⁵

Hints

Hint 1

best[t] = the most a rod of length t can earn.

Hint 2

best[t] = max over the first piece L ≤ min(t, prices.length) of prices[L − 1] + best[t − L].

Hint 3

best[0] = 0; fill t upwards.

Where people lose marks

  • Greedy by price per unit length, which fails when the best ratio does not divide n.
  • Indexing prices by length instead of length − 1.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.