Ctrl K

Cheapest Cut With Close Starts

Hard
You are given an array values and integers parts and spread. Cut the array into exactly parts non-empty contiguous pieces so that every element lands in exactly one piece. The cost of a piece is its **first** element, and the cost of the cut is the sum of the piece costs. There is one rule: piece starts must stay close together. If the second piece starts at index i₁ and the last piece starts at index iₖ₋₁, then iₖ₋₁ − i₁ ≤ spread must hold. Return the minimum cost of a valid cut.
Example 1
values=[4, 9, 2, 7, 1, 8], parts=3, spread=2 → 7

Cut into [4, 9], [2, 7], [1, 8]: the second piece starts at index 2, the third at 4, a gap of 2 ≤ spread. The cost is 4 + 2 + 1 = 7.

Example 2
values=[5, 1, 6, 6, 1], parts=3, spread=1 → 12

Both 1s cannot be used: indices 1 and 4 differ by 3 > 1. The best is [5], [1], [6, 6, 1] or [5, 1, 6], [6], [1], costing 5 + 1 + 6 = 12.

Example 3
values=[3, 3, 3, 3], parts=4, spread=2 → 12
Constraints
  • 3 ≤ len(values) ≤ 10⁵
  • 1 ≤ values[i] ≤ 10⁹
  • 3 ≤ parts ≤ len(values)
  • parts − 2 ≤ spread ≤ len(values) − 2
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsMoving Window Median HardNarrowest Range Touching Every List HardTop Frequency Window Sums: Large Input HardTop-Frequency Window Sums EasyA Level Stretch of Fence Medium
loading Python…
Input
values=[4, 9, 2, 7, 1, 8], parts=3, spread=2
Expected
7

Run checks the first 3 tests in your browser. Submit checks all 184 tests on the server, hidden ones included.