#2208
Minimum Operations to Halve Array Sum
MediumArrayGreedyHeap (Priority Queue)HeapGreedy
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal solution uses a max-heap (priority queue) to efficiently retrieve and halve the largest number in each operation. This approach minimizes the number of operations needed to reduce the sum by at least half.
⚙️
Algorithm
6 steps- 1Step 1: Calculate the initial sum of the array.
- 2Step 2: Create a max-heap from the array elements.
- 3Step 3: While the current sum is greater than half of the initial sum, extract the maximum element from the heap.
- 4Step 4: Halve this maximum element and update the current sum.
- 5Step 5: Insert the halved value back into the heap and increment the operation count.
- 6Step 6: Return the count of operations.
solution.py16 lines
1# Full working Python code
2import heapq
3
4def min_operations(nums):
5 initial_sum = sum(nums)
6 target_sum = initial_sum / 2
7 current_sum = initial_sum
8 operations = 0
9 max_heap = [-num for num in nums]
10 heapq.heapify(max_heap)
11 while current_sum > target_sum:
12 max_num = -heapq.heappop(max_heap)
13 current_sum -= max_num / 2
14 heapq.heappush(max_heap, -max_num / 2)
15 operations += 1
16 return operationsℹ
Complexity note: The time complexity is O(n log n) because we build the max-heap in O(n) time and each operation of extracting and inserting into the heap takes O(log n).
- 1Always halve the largest number to maximize reduction in sum.
- 2Using a max-heap allows for efficient retrieval of the largest element.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.