Put Marbles in Bags — LeetCode 2551 Python Solution
HardGreedyArraySortingHeap (Priority Queue)
- Problem
- #2551
- Pattern
- Heap / Priority Queue
- Reading time
- 2 min
- Source
- leetcode.com
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
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(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.