#2558

Take Gifts From the Richest Pile

Easy
ArrayHeap (Priority Queue)SimulationHeapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n + k log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n + k log n)Space O(n)

Using a max-heap (priority queue) allows us to efficiently retrieve and update the pile with the maximum gifts in logarithmic time. This significantly reduces the number of operations needed.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a max-heap from the gifts array.
  2. 2Step 2: For k seconds, extract the maximum pile, compute its square root, and push it back into the heap.
  3. 3Step 3: After k seconds, sum all remaining gifts in the heap.
solution.py9 lines
1import heapq
2
3def remainingGifts(gifts, k):
4    max_heap = [-gift for gift in gifts]
5    heapq.heapify(max_heap)
6    for _ in range(k):
7        max_gift = -heapq.heappop(max_heap)
8        heapq.heappush(max_heap, -int(max_gift ** 0.5))
9    return -sum(max_heap)

Complexity note: The initial heap creation takes O(n log n), and each of the k operations takes O(log n). Thus, the overall complexity is dominated by O(n log n).

  • 1Using a max-heap allows for efficient retrieval and updating of the maximum gifts pile.
  • 2Understanding how to manipulate heaps is crucial for optimizing problems involving maximum or minimum values.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.