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

The cheapest way to cut a stick

Hard · Target 30 minutes · Dynamic programming · Type asked atGoogleAmazon

A stick of length n must be cut at every position in cuts (distinct, strictly between 0 and n). Making a cut costs the length of the piece being cut at that moment. Return the smallest total cost over all orders of cutting.

Examples

InputOutputWhy
n = 7, cuts = [1,3,4,5]16Cut 3, then 5, then 1, then 4: 7 + 4 + 3 + 2.
n = 9, cuts = [5,6,1,4,2]22The order of cuts matters a lot.
n = 5, cuts = [2]5One cut of the whole stick.

Constraints

  • 2 ≤ n ≤ 10⁶
  • 1 ≤ cuts.length ≤ min(n − 1, 100)
  • All cuts distinct, 0 < cuts[i] < n

Hints

Hint 1

Sort the cuts and add the two ends, 0 and n, as boundaries.

Hint 2

cost(i, j) = cheapest way to make every cut strictly between boundaries i and j.

Hint 3

Choose the first cut k in (i, j): it costs the piece length p[j] − p[i], and splits the work into (i, k) and (k, j).

Where people lose marks

  • A table indexed by stick length, which is far too large.
  • Forgetting to sort the cuts.
  • Greedy middle-first cutting, which is not always optimal.
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.