Take Gifts From the Richest Pile — LeetCode 2558 Python Solution
- Problem
- #2558
- Pattern
- Heap / Priority Queue
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given an integer array gifts denoting the number of gifts in various piles. Every second, you do the following: Choose the pile with the maximum number of gifts.
Example
- Input
- gifts = [25,64,9,4,100], k = 4
- Output
- 29
- Explanation
- The gifts are taken in the following way:
Python solution
class Solution:
def pickGifts(self, gifts: List[int], k: int) -> int:
h = [-v for v in gifts]
heapify(h)
for _ in range(k):
heapreplace(h, -int(sqrt(-h[0])))
return -sum(h)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n + k \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 2558. Take Gifts From the Richest Pile is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Heap (Priority Queue).
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 2558. Take Gifts From the Richest Pile?
- LeetCode 2558. Take Gifts From the Richest Pile is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2558. Take Gifts From the Richest Pile?
- The Python solution on this page runs in O(n + k \times \log n).
- What is the space complexity of LeetCode 2558. Take Gifts From the Richest Pile?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2558. Take Gifts From the Richest Pile cover?
- LeetCode 2558. Take Gifts From the Richest Pile is tagged Array, Simulation and Heap (Priority Queue) on LeetCode.