http://www.lintcode.com/en/problem/maximum-gap/
Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
Return 0 if the array contains less than 2 elements.
Sort is easy but will cost O(nlogn) time. Try to solve it in linear time and space.
Answer:
class Solution {
public:
int maximumGap(vector<int> &num) {
if (num.size() < 2) return 0;
int maxNum = num[0];
int minNum = num[0];
for (int x : num) {
maxNum = max(maxNum, x);
minNum = min(minNum, x);
}
int len = (maxNum - minNum) / num.size() + 1;
vector<vector<int>> buckets((maxNum - minNum) / len + 1);
for (int x : num) {
int i = (x - minNum) / len;
if (buckets[i].empty()) {
buckets[i].reserve(2);
buckets[i].push_back(x);
buckets[i].push_back(x);
} else {
if (x < buckets[i][0]) buckets[i][0] = x;
if (x > buckets[i][1]) buckets[i][1] = x;
}
}
int gap = 0;
int prev = 0;
for (int i = 1; i < buckets.size(); i++) {
if (buckets[i].empty()) continue;
gap = max(gap, buckets[i][0] - buckets[prev][1]);
prev = i;
}
return gap;
}
};