-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path30. Minimize Deviation in Array
52 lines (42 loc) · 1.16 KB
/
30. Minimize Deviation in Array
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
class Solution {
public int minimumDeviation(int[] nums) {
PriorityQueue<Integer> pq=new PriorityQueue<>((a,b)->b-a);
int min=Integer.MAX_VALUE;
for(int i:nums){
if(i%2==1) i*=2;
min=Math.min(min,i);
pq.add(i);
}
int diff=Integer.MAX_VALUE;
while(pq.peek()%2==0){
int max=pq.remove();
diff=Math.min(diff,max-min);
min=Math.min(max/2,min);
pq.add(max/2);
}
return Math.min(diff,pq.peek()-min);
}
}
class Solution {
public int minimumDeviation(int[] nums) {
TreeSet<Integer> ts=new TreeSet<>();
for(int i:nums){
if(i%2==1) i*=2;
ts.add(i);
}
int diff=Integer.MAX_VALUE;
while(true){
int max=ts.last();
int min=ts.first();
diff=Math.min(diff,max-min);
if(max%2==0){
ts.remove(max);
ts.add(max/2);
}
else{
break;
}
}
return diff;
}
}