-
Notifications
You must be signed in to change notification settings - Fork 0
/
mh_problem.py
74 lines (53 loc) · 1.75 KB
/
mh_problem.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
"""Solution to https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array """
from typing import List
class Solution:
def maxProduct(self, nums: List[int]) -> int:
MaxHeap.heapsort(nums)
return (nums[len(nums) - 1] - 1) * (nums[len(nums) - 2] - 1)
class MaxHeap:
def __init__(self):
self._data = []
self._heap_size = 0
def __len__(self):
return self._heap_size
def _swap(self, i, j):
self._data[i], self._data[j] = self._data[j], self._data[i]
@staticmethod
def _parent(i):
return (i - 1) // 2
@staticmethod
def _left(i):
return 2 * i + 1
@staticmethod
def _right(i):
return 2 * i + 2
def _max_heapify(self, i):
data = self._data
size = self._heap_size
l = self._left(i)
r = self._right(i)
if l < size and data[l] > data[i]:
largest = l
else:
largest = i
if r < size and data[r] > data[largest]:
largest = r
self._swap(i, largest)
if largest != i:
self._max_heapify(largest)
def build_max_heap(self, data):
self._data = data
self._heap_size = len(data)
for i in range(self._heap_size // 2 - 1, -1, -1):
self._max_heapify(i)
@staticmethod
def heapsort(data):
max_heap = MaxHeap()
max_heap.build_max_heap(data)
for i in range(max_heap._heap_size - 1, max_heap._heap_size - 3, -1):
max_heap._swap(0, i)
max_heap._heap_size -= 1
max_heap._max_heapify(0)
if __name__ == '__main__':
nums = [3, 4, 5, 2]
print(Solution().maxProduct(nums))