819. Stick Cutter

A ribbon shop has one ribbon of length centimetres and a list cuts of positions, measured from the left end, where the customer wants it cut. Each cut splits one current piece in two, and its price equals the current length of the piece you are cutting. You may perform the cuts in any order.

Positions that are not strictly between 0 and length need no cutting and are ignored; a position listed several times is cut only once. Return the minimum total price needed to make every required cut. If nothing needs cutting, return 0.

Aim for time O(m^3) and space O(m^2), where m is the number of distinct valid positions.

Example 1

Input:
length = 30, cuts = [14,6,22]
Output:
60
Explanation:

Cutting at 14 first costs 30, then the piece of length 14 is cut at 6 for 14 and the piece 16 is cut at 22 for 16, giving 60; other orders cost more.

Example 2

Input:
length = 50, cuts = [20,35,10,45]
Output:
115
Explanation:

Cut at 20 (cost 50), then at 35 (cost 30), then at 10 (cost 20) and at 45 (cost 15) for a total of 115 - the cheapest order.

Constraints

1 ≤ length ≤ 106

0 ≤ cuts.length ≤ 300

-106 ≤ cuts[i] ≤ 2*106

The answer fits in a 32-bit signed integer.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(m^3)
Space
O(m^2)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…