Take Gifts From the Richest Pile — LeetCode 2558 Python Solution

EasyArraySimulationHeap (Priority Queue)
Problem
#2558
Reading time
2 min

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

Python
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

MeasureComplexity
TimeO(n + k \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 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.

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