Minimum Difference in Sums After Removal of Elements LeetCode solution in Python

1
class Solution:
2
def minimumDifference(self, nums: List[int]) -> int:
3
h = heapq
4
k = len(nums) // 3
5
min_heap, max_heap, min_sol, max_sol, min_sum, max_sum, sol = (
6
[],
7
[],
8
[],
9
[],
10
0,
11
0,
12
[],
13
)
14
h.heapify(max_heap), h.heapify(min_heap)
15
for x in nums[:-k]:
16
h.heappush(min_heap, -x)
17
min_sum += x
18
if len(min_heap) > k:
19
min_sum += h.heappop(min_heap)
20
min_sol.append(min_sum)
21
for x in nums[::-1][:-k]:
22
h.heappush(max_heap, x)
23
max_sum += x
24
if len(max_heap) > k:
25
max_sum -= h.heappop(max_heap)
26
max_sol.append(max_sum)
27
min_sol = min_sol[k - 1 :]
28
max_sol = max_sol[k - 1 :][::-1]
29
return min(
30
min_value - max_value for min_value, max_value in zip(min_sol, max_sol)
31
)

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0