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.
- If there is more than one pile with the maximum number of gifts, choose any.
- Leave behind the floor of the square root of the number of gifts in the pile. Take the rest of the gifts.
Return the number of gifts remaining afterk
seconds.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
1 <= gifts.length <= 10^3
1 <= gifts[i] <= 10^9
1 <= k <= 10^3
Solution
Method 1 - Using Max Heap
To solve this problem, we need to repeatedly choose the pile with the maximum number of gifts, and then update the pile according to the described process. The efficient way to do this is to use a max-heap data structure since it allows us to efficiently retrieve and update the maximum element.
Steps
- Convert all elements in the
gifts
array to negative and build a max-heap (using Python’sheapq
which is a min-heap by default). - Perform the operation
k
times:- Extract the maximum element from the heap.
- Calculate the floor of the square root of this element.
- Negate and push the updated value back into the heap.
- The sum of all elements left in the heap after
k
seconds is the desired result.
Video explanation
Here is the video explaining this method in detail. Please check it out:
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n + k log n)
, wheren
is length of the array.O(n)
for building the heap, and it takesO(log n)
for heap push and pop operations, and we do itk
times, henceO(k log(n))
, so total time complexity isO(n + k log n)
. - 🧺 Space complexity:
O(n)
to store all elements of array in heap