All problems
0955HardArrayGreedySortingHeap (Priority Queue)

Splitting a Line of Marbles Into Bags

Tracked in this browser only
Write code

Trains the technique from

LeetCode 2551Put Marbles in Bags

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

Marbles stand in a line with weights weights. They are put into exactly k bags so that every bag holds a run of neighbouring marbles, no bag is empty, and every marble goes into a bag.

A bag's cost is the weight of its first marble plus the weight of its last. The score of a way of bagging is the total of its bags' costs.

Return the difference between the largest and the smallest score any bagging can have.

Examples

Example 1

Input
weights = [14, 3, 27, 9, 41, 6], k = 3
Output
50

Two cuts are placed among the five neighbouring pairs, whose totals are 17, 30, 36, 50 and 47. The largest score takes the two heaviest, 50 and 47, and the smallest takes 17 and 30, so the difference is 50.

Example 2

Input
weights = [5, 9], k = 2
Output
0

There is only one place to cut, so every bagging scores the same.

Example 3

Input
weights = [5], k = 1
Output
0

A single bag needs no cuts at all.

Constraints

  • 1 <= weights.length <= 10^5
  • 1 <= k <= weights.length
  • 1 <= weights[i] <= 10^9

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def put_marbles(weights: list[int], k: int) -> int:
Java
public long putMarbles(int[] weights, int k)
September 7
Apply