Skip to content

Commit a3141a8

Browse files
authored
Merge pull request #25 from JAYKALIA007/main
solution 7 week 3
2 parents 3393af4 + 99463ba commit a3141a8

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed

Questions/week 3/solution_7.cpp

+88
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
#define pii pair<int, int>
5+
class Solution {
6+
7+
public:
8+
int getMinDiff(int arr[], int n, int k)
9+
{
10+
11+
if (n == 1)
12+
return 0;
13+
14+
sort(arr, arr + n);
15+
16+
vector<pii> t;
17+
18+
map<int, int> m;
19+
20+
int n_ = 1;
21+
22+
t.push_back(pii(arr[0] + k, arr[0]));
23+
24+
t.push_back(pii(arr[0] - k, arr[0]));
25+
26+
for (int i = 1; i < n; i++) {
27+
28+
if (arr[i] != arr[i - 1]) {
29+
30+
t.push_back(pii(arr[i] + k, arr[i]));
31+
32+
t.push_back(pii(arr[i] - k, arr[i]));
33+
34+
m[arr[i]] = 0;
35+
36+
n_++;
37+
}
38+
}
39+
40+
sort(t.begin(), t.end());
41+
42+
int l = 0, r = 0;
43+
44+
int ans = t[t.size() - 1].first - t[0].first;
45+
46+
int count = 0;
47+
48+
while (r < t.size()) {
49+
50+
while (r < t.size() and count < n_) {
51+
52+
if (m[t[r].second] == 0)
53+
count++;
54+
55+
m[t[r].second]++;
56+
57+
r++;
58+
}
59+
60+
if (r == t.size() and count < n_)
61+
break;
62+
63+
ans = min(ans, t[r - 1].first - t[l].first);
64+
65+
while (l <= r and count >= n_) {
66+
67+
if (m[t[l].second] == 1)
68+
count--;
69+
70+
m[t[l].second]--;
71+
72+
ans = min(ans, t[r - 1].first - t[l].first);
73+
74+
l++;
75+
}
76+
}
77+
78+
return ans;
79+
}
80+
};
81+
82+
int main()
83+
{
84+
Solution s;
85+
int k = 5, n = 10;
86+
int arr[n] = { 8, 1, 5, 4, 7, 5, 7, 9, 4, 6 };
87+
cout << s.getMinDiff(arr, n, k);
88+
}

0 commit comments

Comments
 (0)