Problem Description
Given an array gifts representing the number of gifts in several piles, every second choose the pile with the maximum number of gifts and reduce its count to the floor of its square root. After k seconds, return the total number of gifts remaining.
Key Insights
- Use a max-heap (priority queue) to quickly access the pile with the maximum gifts.
- Since some languages (like Python) provide a min-heap by default, store negative values to simulate a max-heap.
- Each iteration reduces the largest pile using floor(sqrt(value)).
- Simulation runs for k iterations, updating the heap at each step.
Space and Time Complexity
Time Complexity: O(k log n) where n is the number of piles. Space Complexity: O(n) for maintaining the heap.
Solution
We use a max-heap to store the gifts. For each of the k seconds, we pop the largest element, compute its new value using the floor of its square root, and push it back into the heap. Finally, we sum all the elements in the heap to produce the result.