Skip to content

Commit 7c52d97

Browse files
authored
Create minimum-operations-to-halve-array-sum.py
1 parent 3b026e7 commit 7c52d97

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Time: O(nlogn)
2+
# Space: O(n)
3+
4+
import heapq
5+
6+
7+
# heap
8+
class Solution(object):
9+
def halveArray(self, nums):
10+
"""
11+
:type nums: List[int]
12+
:rtype: int
13+
"""
14+
target = sum(nums)/2.0
15+
max_heap = [-x for x in nums]
16+
heapq.heapify(max_heap)
17+
result = 1
18+
while max_heap:
19+
x = -heapq.heappop(max_heap)/2.0
20+
target -= x
21+
if target <= 0.0:
22+
break
23+
heapq.heappush(max_heap, -x)
24+
result += 1
25+
return result

0 commit comments

Comments
 (0)