-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminimize-deviation-in-array.go
More file actions
74 lines (57 loc) · 1.02 KB
/
Copy pathminimize-deviation-in-array.go
File metadata and controls
74 lines (57 loc) · 1.02 KB
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
package minimizedeviationinarray
import (
"container/heap"
"math"
)
type PriorityQueue []int
func (pq PriorityQueue) Len() int {
return len(pq)
}
func (pq PriorityQueue) Less(i, j int) bool {
return pq[i] > pq[j]
}
func (pq PriorityQueue) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
}
func (pq *PriorityQueue) Push(x interface{}) {
*pq = append(*pq, x.(int))
}
func (pq *PriorityQueue) Pop() interface{} {
item := (*pq)[len(*pq)-1]
*pq = (*pq)[0 : len(*pq)-1]
return item
}
func minimumDeviation(nums []int) int {
min := math.MaxInt32
res := math.MaxInt32
pq := PriorityQueue{}
for i := 0; i < len(nums); i++ {
if nums[i]%2 == 1 {
nums[i] *= 2
}
if nums[i] < min {
min = nums[i]
}
}
for i := 0; i < len(nums); i++ {
for nums[i]%2 == 0 && nums[i] >= min*2 {
nums[i] /= 2
}
heap.Push(&pq, nums[i])
}
for true {
n := heap.Pop(&pq).(int)
if (n - min) < res {
res = n - min
}
if n%2 == 1 {
break
}
if n/2 < min {
min = n / 2
}
n /= 2
heap.Push(&pq, n)
}
return res
}