forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximumGap.cpp
More file actions
37 lines (37 loc) · 1.04 KB
/
MaximumGap.cpp
File metadata and controls
37 lines (37 loc) · 1.04 KB
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
class Solution {
public:
int maximumGap(vector<int> &num) {
if(num.size()<2) {
return 0;
}
if(num.size()==2) {
return abs(num[0]-num[1]);
}
int minV = num[0];
int maxV = num[0];
for(auto it : num) {
minV = min(minV, it);
maxV = max(maxV, it);
}
int n = (int)num.size();
vector<int> mins(n-1, INT_MAX);
vector<int> maxs(n-1, INT_MIN);
vector<bool> hasElement(n-1,false);
for(auto it: num) {
int bucketNo = int(double(it - minV)/(maxV-minV+1)*(n-1));
hasElement[bucketNo] = true;
mins[bucketNo] = min(mins[bucketNo], it);
maxs[bucketNo] = max(maxs[bucketNo], it);
}
int last = minV;
int maxG = 0;
for(int i=0;i<n-1;i++) {
if(hasElement[i]) {
//cout << mins[i]-last << endl;
maxG = max(maxG, mins[i]-last);
last = maxs[i];
}
}
return maxG;
}
};