Input: gifts =[25,64,9,4,100], k =4Output: 29Explanation:
The gifts are taken in the following way:- In the first second, the last pile is chosen and 10 gifts are left behind.- Then the second pile is chosen and 8 gifts are left behind.- After that the first pile is chosen and 5 gifts are left behind.- Finally, the last pile is chosen again and 3 gifts are left behind.The final remaining gifts are [5,8,9,4,3], so the total number of gifts remaining is29.
Input: gifts =[1,1,1,1], k =4Output: 4Explanation:
In thiscase, regardless which pile you choose, you have to leave behind 1 gift in each pile.That is, you can't take any pile with you.So, the total gifts remaining are 4.
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.
classSolution {
publiclongpickGifts(int[] gifts, int k) {
PriorityQueue<Integer> maxHeap =new PriorityQueue<>((a, b) -> b - a); // MAX-HEAP// Add all gift counts to the max-heapfor (int gift : gifts) {
maxHeap.add(gift);
}
// Perform the operation k timesfor (int i = 0; i < k; i++) {
int maxGift = maxHeap.poll();
int remainingGift = (int) Math.sqrt(maxGift);
maxHeap.add(remainingGift);
}
// Sum all remaining gifts in the heaplong sum = 0;
while (!maxHeap.isEmpty()) {
sum += maxHeap.poll();
}
return sum;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defpick_gifts(self, gifts: List[int], k: int) -> int:
max_heap = []
for gift in gifts:
heappush(max_heap, -gift) # We use negative values to simulate a max-heapfor _ in range(k):
max_gift =-heappop(max_heap)
remaining_gift = math.isqrt(max_gift)
heappush(max_heap, -remaining_gift)
ans =-sum(max_heap)
return int(ans)
⏰ Time complexity: O(n + k log n), where n is length of the array. O(n) for building the heap, and it takes O(log n) for heap push and pop operations, and we do it k times, hence O(k log(n)), so total time complexity is O(n + k log n).
🧺 Space complexity: O(n) to store all elements of array in heap