#1962
Remove Stones to Minimize the Total
MediumArrayGreedyHeap (Priority Queue)Greedy AlgorithmsHeap (Priority Queue)
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(k log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(k log n)Space O(n)
In the optimal solution, we use a max-heap (priority queue) to efficiently retrieve and update the pile with the maximum stones. This allows us to perform the k operations in a more efficient manner.
⚙️
Algorithm
4 steps- 1Step 1: Create a max-heap from the piles array.
- 2Step 2: For k times, extract the maximum pile from the heap.
- 3Step 3: Remove floor(max / 2) stones from this pile and push the updated pile back into the heap.
- 4Step 4: After k operations, sum the remaining stones in the heap.
solution.py9 lines
1import heapq
2
3def minStoneSum(piles, k):
4 max_heap = [-x for x in piles]
5 heapq.heapify(max_heap)
6 for _ in range(k):
7 max_pile = -heapq.heappop(max_heap)
8 heapq.heappush(max_heap, -(max_pile - max_pile // 2))
9 return -sum(max_heap)ℹ
Complexity note: The time complexity is O(k log n) because each of the k operations involves extracting the maximum from the heap and inserting the updated pile back, both of which take logarithmic time relative to the number of piles.
- 1Always target the pile with the maximum stones to minimize the total effectively.
- 2Using a max-heap allows for efficient retrieval and updating of the maximum pile.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.