Put Marbles in Bags — LeetCode 2551 Python Solution

HardGreedyArraySortingHeap (Priority Queue)
Problem
#2551
Reading time
2 min

The problem

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

Example

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.

Python solution

Python
class Solution:
    def putMarbles(self, weights: List[int], k: int) -> int:
        arr = sorted(a + b for a, b in pairwise(weights))
        return sum(arr[len(arr) - k + 1 :]) - sum(arr[: k - 1])

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(n) auxiliary

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 2551. Put Marbles in Bags is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2551. Put Marbles in Bags?
LeetCode 2551. Put Marbles in Bags is rated Hard on LeetCode.
What is the time complexity of LeetCode 2551. Put Marbles in Bags?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 2551. Put Marbles in Bags?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2551. Put Marbles in Bags cover?
LeetCode 2551. Put Marbles in Bags is tagged Greedy, Array, Sorting and Heap (Priority Queue) on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview