164. Maximum Gap
Input: [3,6,9,1]
Output: 3
Explanation: The sorted form of the array is [1,3,6,9], either
(3,6) or (6,9) has the maximum difference 3.Input: [10]
Output: 0
Explanation: The array contains less than 2 elements, therefore return 0.// Bucket Sort
int maximumGap(vector<int>& nums) { // time: O(n); space: O(n)
int n = nums.size();
if (n < 2) return 0; // invalid input
int mx = nums[0], mn = nums[0];
// find the max/min in the input
for (int num : nums) {
mx = max(mx, num);
mn = min(mn, num);
}
// the minimum possible gap
int gap = max(1, (mx - mn) / (n - 1)); // make sure the value is at least 1
int m = (mx - mn) / gap + 1;
vector<vector<int> > buckets(m);
// put numbers into buckets
for (int num : nums) {
int idx = (num - mn) / gap;
if (buckets[idx].empty()) {
buckets[idx] = vector<int>(2, num);
} else {
buckets[idx][0] = min(buckets[idx][0], num);
buckets[idx][1] = max(buckets[idx][1], num);
}
}
int prev = 0;
gap = 0;
// scan and find the max gap
for (int i = 0; i < m; ++i) {
if (buckets[i].empty()) continue;
if (buckets[i][0] - buckets[prev][1] > gap)
gap = buckets[i][0] - buckets[prev][1];
prev = i;
}
return gap;
}Last updated