2558. Take Gifts From the Richest Pile
EasyView on LeetCode
Time: O(n + k log n)
Space: O(n)
Advertisement
Intuition
Pick n gifts: each pick replaces max with floor(sqrt(max)). Use max-heap.
Algorithm
- 1Max-heap. Repeat k times: pop max, push floor(sqrt(max)). Sum remaining.
Common Pitfalls
- •After k operations, sum all remaining elements. Use PriorityQueue (max-heap).
2558.cs
C#
// Approach: Max-heap; k times take max and push floor(sqrt(max)) back.
// Time: O(n + k log n) Space: O(n)
public class Solution
{
public long PickGifts(int[] gifts, int k)
{
long ans = 0;
PriorityQueue<int, int> maxHeap = new PriorityQueue<int, int>();
foreach (int gift in gifts)
maxHeap.Enqueue(gift, -gift); // Use negative priority for max-heap behavior
for (int i = 0; i < k; ++i)
{
int maxGift = maxHeap.Dequeue();
int squaredMax = (int)Math.Sqrt(maxGift);
maxHeap.Enqueue(squaredMax, -squaredMax);
}
while (maxHeap.TryDequeue(out int result, out int _))
ans += result;
return ans;
}
}Advertisement
Was this solution helpful?