Minimum Operations to Halve Array Sum LeetCode solution in Python

1
class Solution:
2
def halveArray(self, nums: List[int]) -> int:
3
# Creating empty heap
4
maxHeap = []
5
heapify(maxHeap) # Creates minHeap
6

7
totalSum = 0
8
for i in nums:
9
# Adding items to the heap using heappush
10
# for maxHeap, function by multiplying them with -1
11
heappush(maxHeap, -1 * i)
12
totalSum += i
13

14
requiredSum = totalSum / 2
15
minOps = 0
16

17
while totalSum > requiredSum:
18
x = -1 * heappop(maxHeap) # Got negative value make it positive
19
x /= 2
20
totalSum -= x
21
heappush(maxHeap, -1 * x)
22
minOps += 1
23

24
return minOps

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0