Minimum Operations to Halve Array Sum — LeetCode 2208 Python Solution
MediumGreedyArrayHeap (Priority Queue)
- Problem
- #2208
- Pattern
- Heap / Priority Queue
- Reading time
- 3 min
- Source
- leetcode.com
The problem
You are given an array nums of positive integers. In one operation, you can choose any number from nums and reduce it to exactly half the number.
Example
- Input
- nums = [5,19,8,1]
- Output
- 3
- Explanation
- The initial sum of nums is equal to 5 + 19 + 8 + 1 = 33.
Python solution
Python
class Solution:
def halveArray(self, nums: List[int]) -> int:
s = sum(nums) / 2
pq = []
for x in nums:
heappush(pq, -x)
ans = 0
while s > 0:
t = -heappop(pq) / 2
s -= t
heappush(pq, -t)
ans += 1
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(n) auxiliary |
Pattern: Heap / Priority Queue
Keep only the best k elements, or always pull the smallest, in log time. LeetCode 2208. Minimum Operations to Halve Array Sum is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.
The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2208. Minimum Operations to Halve Array Sum?
- LeetCode 2208. Minimum Operations to Halve Array Sum is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2208. Minimum Operations to Halve Array Sum?
- The Python solution on this page runs in O(n \times \log n).
- What is the space complexity of LeetCode 2208. Minimum Operations to Halve Array Sum?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2208. Minimum Operations to Halve Array Sum cover?
- LeetCode 2208. Minimum Operations to Halve Array Sum is tagged Greedy, Array and Heap (Priority Queue) on LeetCode.