Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit a2bb627

Browse filesBrowse files
authored
Create 30 minDeviationArray.cpp
1 parent 413c86b commit a2bb627
Copy full SHA for a2bb627

File tree

Expand file treeCollapse file tree

1 file changed

+35
-0
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+35
-0
lines changed

‎January 2021/30 minDeviationArray.cpp

Copy file name to clipboard
+35Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Solution {
2+
public:
3+
int minimumDeviation(vector<int>& nums) {
4+
5+
// Step 1 :- increase all elements to as maximum as it can and track the minn number and also the result
6+
int N = nums.size();
7+
int maxx = INT_MIN, minn = INT_MAX;
8+
for(int i = 0; i < N; i++){
9+
if((nums[i])%2 != 0){
10+
nums[i] *= 2;
11+
}
12+
maxx = max(maxx, nums[i]);
13+
minn = min(minn, nums[i]);
14+
}
15+
int min_deviation = maxx - minn;
16+
17+
// Step 2 :- Insert into max_heap and try to decrease the maxx as much as u can
18+
priority_queue<int>pq;
19+
for(int i = 0; i < N; i++){
20+
pq.push(nums[i]);
21+
}
22+
23+
while((pq.top())%2 == 0){
24+
int top = pq.top(); pq.pop();
25+
min_deviation = min(min_deviation, top - minn);
26+
top /= 2;
27+
minn = min(minn, top);
28+
pq.push(top);
29+
}
30+
min_deviation = min(min_deviation, pq.top() - minn);
31+
32+
// Step 3 :- return maxx - minn;
33+
return min_deviation ;
34+
}
35+
};

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.