Skip to content

Commit a187a26

Browse files
committed
Solution as on 19-02-2022 06:30 am
1 parent 92de138 commit a187a26

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
// 1675.✅ Minimize Deviation in Array
2+
3+
class Solution
4+
{
5+
public:
6+
int minimumDeviation(vector<int> &nums)
7+
{
8+
int n = nums.size();
9+
int mx = INT_MIN, mn = INT_MAX;
10+
11+
// Increasing all elements to as maximum as it can and tranck the minimum,
12+
// number and also the resutl
13+
for (int i = 0; i < n; ++i)
14+
{
15+
if ((nums[i] % 2) != 0) // multiplication by 2 if nums[i] is odd
16+
nums[i] *= 2; // maximising all odd numbers
17+
18+
mx = max(mx, nums[i]);
19+
mn = min(mn, nums[i]);
20+
}
21+
22+
int min_deviation = mx - mn;
23+
24+
priority_queue<int> pq;
25+
// Inserting into Priority queue (Max Heap) and try to decrease as much we can
26+
for (int i = 0; i < n; ++i)
27+
{
28+
pq.push(nums[i]);
29+
}
30+
31+
while ((pq.top()) % 2 == 0)
32+
{
33+
int top = pq.top();
34+
pq.pop(); // popped the top element
35+
36+
min_deviation = min(min_deviation, top - mn);
37+
top /= 2;
38+
mn = min(mn, top); // updating min
39+
pq.push(top); // pushing again the top as we have to minimize the max
40+
}
41+
42+
min_deviation = min(min_deviation, pq.top() - mn);
43+
44+
// we are returning mx - mn
45+
46+
return min_deviation;
47+
}
48+
};
49+
50+
class Solution
51+
{
52+
public:
53+
int minimumDeviation(vector<int> &nums)
54+
{
55+
set<int> s;
56+
57+
// Storing all elements in sorted order
58+
// insert even directly and odd with one time multiplication
59+
// and it will become even
60+
for (int i = 0; i < nums.size(); ++i)
61+
{
62+
if (nums[i] % 2 == 0)
63+
s.insert(nums[i]);
64+
65+
else
66+
// Odd number are transformed
67+
// using 2nd operation
68+
s.insert(nums[i] * 2);
69+
}
70+
71+
// maximum - minimun
72+
int diff = *s.rbegin() - *s.begin();
73+
74+
// run the loop untill difference is minimized
75+
while (*s.rbegin() % 2 == 0)
76+
{
77+
78+
// Maximum element of the set
79+
int x = *s.rbegin();
80+
s.erase(x);
81+
// remove begin element and inserted half of it for minimizing
82+
s.insert(x / 2);
83+
84+
diff = min(diff, *s.rbegin() - *s.begin());
85+
}
86+
return diff;
87+
}
88+
};

0 commit comments

Comments
 (0)