-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1675.minimize-deviation-in-array.py
51 lines (43 loc) · 1.26 KB
/
1675.minimize-deviation-in-array.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
"""
Description: Minimize Deviation in Array
Version: 1
Author: Taki Guan
Date: 2021-01-30 21:22:47
LastEditors: Taki Guan
LastEditTime: 2021-01-31 19:44:10
"""
#
# @lc app=leetcode id=1675 lang=python3
#
# [1675] Minimize Deviation in Array
#
# @lc code=start
from typing import List
from heapq import *
class Solution:
def minimumDeviation(self, nums: List[int]) -> int:
heap = []
# 构建数组,数组中为nums数组中每个元素及这个元素的最小及最大值
for num in nums:
if num % 2 == 0:
n = num
while n % 2 == 0:
n //= 2
heap.append([n, num])
else:
heap.append([num, num * 2])
# 从最小值中取得最大值
max_value = max([val[0] for val in heap])
heapify(heap)
ans = float("inf")
while True:
# 从所有数组中取得最小值中的最小值
val, bound = heappop(heap)
# 如果该值超出最大值,则跳出循环
if val >= bound:
break
max_value = max(val * 2, max_value)
heappush(heap, [val * 2, bound])
ans = min(ans, max_value - heap[0][0])
return ans
# @lc code=end