> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Put Marbles in Bags Python Solution with Tests

> Tested Python solution for LeetCode 2551 with 18 pytest cases. Generate a practice environment with lcpy.

LeetCode 2551, [Hard](/catalog/hard). Topics: [Array](/catalog/topics/array), [Greedy](/catalog/topics/greedy), [Sorting](/catalog/topics/sorting), [Heap (Priority Queue)](/catalog/topics/heap-priority-queue). [View on LeetCode](https://leetcode.com/problems/put-marbles-in-bags/description/).

Generate this problem as a practice environment: tested reference solution, 18 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 2551   # by problem number
lcpy gen -s put_marbles_in_bags   # by problem name
```

## Problem

You have `k` bags. You are given a **0-indexed** integer array `weights` where `weights[i]` is the weight of the `i`th marble. You are also given the integer `k`.

Divide the marbles into the `k` bags according to the following rules:

* No bag is empty.
* If the `i`th marble and `j`th marble are in a bag, then all marbles with an index between the `i`th and `j`th indices should also be in that same bag.
* If a bag consists of all the marbles with an index from `i` to `j` inclusively, then the cost of the bag is `weights[i] + weights[j]`.

The **score** after distributing the marbles is the sum of the costs of all the `k` bags.

Return the difference between the maximum and minimum scores among marble distributions.

### Examples

```
Input: weights = [1,3,5,1], k = 2
Output: 4
Explanation:
The distribution [1],[3,5,1] results in the minimal score of (1+1) + (3+1) = 6.
The distribution [1,3],[5,1], results in the maximal score of (1+3) + (5+1) = 10.
Thus, we return their difference 10 - 6 = 4.
```

```
Input: weights = [1, 3], k = 2
Output: 0
Explanation: The only distribution possible is [1],[3].
Since both the maximal and minimal score are the same, we return 0.
```

### Constraints

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

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/put_marbles_in_bags/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/put_marbles_in_bags/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n log n)
    # Space: O(n)
    def put_marbles(self, weights: list[int], k: int) -> int:
        if k == 1:
            return 0
        pair_sums = sorted(weights[i] + weights[i + 1] for i in range(len(weights) - 1))
        splits = k - 1
        return sum(pair_sums[-splits:]) - sum(pair_sums[:splits])
```

## Complexity

| Time | Space |
| - | - |
| O(n log n) | O(n) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.