15% off all plans & roadmaps Use code
See plansLeetCode 2558 · Solution & editorial
You are given an integer array gifts denoting the number of gifts in various piles. Every second, you do the following:
Take Gifts From the Richest Pile is a Heap (Priority Queue) Patterns problem, in the Top K Elements (Selection/Frequency) subpattern. The pattern covers top K elements, K-way merge, two heaps for median, and scheduling
Find top K elements using heap. Solve kth largest, top K frequent, and k closest points problems.
The reference solution runs in O(k log n + n) time and O(n) space.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Take Gifts From the Richest Pile is a Heap (Priority Queue) Patterns problem, in the Top K Elements (Selection/Frequency) subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.