You are given a 0-indexed integer array gifts
denoting the number of gifts in several piles. Every second, you pick the pile with the maximum gifts and take half of them (half the gifts are rounded down).
Your job is to return the number of gifts remaining after k
seconds.
gifts
and the value of k
?
gifts
and the value of k
can be assumed to be reasonably large but manageable within efficient computation time.heapq
library provides a min-heap, so we can store negative values to simulate a max-heap.k
:
k
seconds and return the result.import heapq
def pickGifts(gifts, k):
max_heap = [-gift for gift in gifts]
heapq.heapify(max_heap)
for _ in range(k):
max_gifts = -heapq.heappop(max_heap)
remaining_gifts = max_gifts - (max_gifts // 2)
heapq.heappush(max_heap, -remaining_gifts)
remaining_total = -sum(max_heap)
return remaining_total
# Example usage:
gifts = [5, 4, 9]
k = 3
print(pickGifts(gifts, k)) # Expected output depends on the processing of the function
O(n)
time, where n
is the number of piles.k
operations involves extracting the max (which takes O(log n)
) and pushing an updated value back (which also takes O(log n)
).O(n + k log n)
.This approach ensures that the solution is efficient and scalable within typical problem constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?