Skip to content

Commit 40c6d6d

Browse files
authored
Create 1675-minimize-deviation-in-array.cpp
1 parent ef15ee9 commit 40c6d6d

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/*
2+
You are given an array nums of n positive integers.
3+
4+
You can perform two types of operations on any element of the array any number of times:
5+
6+
If the element is even, divide it by 2.
7+
For example, if the array is [1,2,3,4], then you can do this operation on the last element, and the array will be [1,2,3,2].
8+
If the element is odd, multiply it by 2.
9+
For example, if the array is [1,2,3,4], then you can do this operation on the first element, and the array will be [2,2,3,4].
10+
11+
The deviation of the array is the maximum difference between any two elements in the array.
12+
13+
Return the minimum deviation the array can have after performing some number of operations.
14+
Ex. Input: nums = [1,2,3,4]
15+
Output: 1
16+
Explanation: You can transform the array to [1,2,3,2], then to [2,2,3,2], then the deviation will be 3 - 2 = 1.
17+
18+
Time : O(N);
19+
Space : O(N);
20+
*/
21+
22+
class Solution {
23+
public:
24+
int minimumDeviation(vector<int>& nums) {
25+
priority_queue <int> pq;
26+
int minimum = INT_MAX;
27+
for(auto i : nums) {
28+
if(i & 1)
29+
i *= 2;
30+
minimum = min(minimum, i);
31+
pq.push(i);
32+
}
33+
int res = INT_MAX;
34+
while(pq.top() % 2 == 0) {
35+
int val = pq.top();
36+
res = min(res, val - minimum);
37+
minimum = min(val/2, minimum);
38+
pq.pop();
39+
pq.push(val/2);
40+
}
41+
return min(res, pq.top() - minimum);
42+
}
43+
};

0 commit comments

Comments
 (0)