Put Marbles in Bags
Real-world version: Splitting a Line of Marbles Into BagsThe statement here is our own: the same inputs, outputs and technique.
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 starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def put_marbles(weights: list[int], k: int) -> int:public long putMarbles(int[] weights, int k)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 10 test cases: 10 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Make Array Zero by Subtracting Equal AmountsReal-world version: Rounds Needed to Clear Every ReadingEasy
- Meeting Rooms IIReal-world version: Peak Charging Bay DemandMedium
- Task SchedulerReal-world version: Press Die CooldownMedium
- Maximum Number of Events That Can Be AttendedReal-world version: Most Inspections BookedMedium