Description
Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
Try to solve it in linear time/space.
Return 0 if the array contains less than 2 elements.
You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.
Explanation
See here
Solution 1 - Sort
// OJ: https://leetcode.com/problems/maximum-gap
// Auther: github.com/lzl124631x
// Time: O(NlogN)
// Space: O(1)
class Solution {
public:
int maximumGap(vector<int>& nums) {
sort(nums.begin(), nums.end());
int ans = 0;
for (int i = 1; i < nums.size(); ++i) ans = max(ans, nums[i] - nums[i - 1]);
return ans;
}
};
Solution 2 - Radix Sort
// OJ: https://leetcode.com/problems/maximum-gap
// Auther: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
// Ref: https://leetcode.com/articles/maximum-gap
class Solution {
public:
int maximumGap(vector<int>& nums) {
if (nums.size() < 2) return 0;
int maxVal = *max_element(nums.begin(), nums.end());
vector<int> aux(nums.size());
for (int exp = 1, radix = 10; maxVal / exp > 0; exp *= radix) {
vector<int> cnt(radix, 0);
for (int n : nums) cnt[(n / exp) % radix]++;
for (int i = 1; i < cnt.size(); ++i) cnt[i] += cnt[i - 1];
for (int i = nums.size() - 1; i >= 0; --i) aux[--cnt[(nums[i] / exp) % radix]] = nums[i];
nums = aux;
}
int ans = 0;
for (int i = 1; i < nums.size(); ++i) ans = max(ans, nums[i] - nums[i - 1]);
return ans;
}
};
Solution 3 - Buckets and The Pigeonhole Principle
// OJ: https://leetcode.com/problems/maximum-gap
// Auther: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
// Ref: https://discuss.leetcode.com/topic/5999/bucket-sort-java-solution-with-explanation-o-n-time-and-space
class Solution {
public:
int maximumGap(vector<int>& nums) {
if (nums.size() < 2) return 0;
int N = nums.size(), minVal = INT_MAX, maxVal = INT_MIN;
for (int n : nums) {
minVal = min(minVal, n);
maxVal = max(maxVal, n);
}
int gap = ceil((double)(maxVal - minVal) / (N - 1));
vector<int> mins(N - 1, INT_MAX), maxes(N - 1, INT_MIN);
for (int n : nums) {
if (n == minVal || n == maxVal) continue;
int i = (n - minVal) / gap;
mins[i] = min(mins[i], n);
maxes[i] = max(maxes[i], n);
}
int ans = INT_MIN, prev = minVal;
for (int i = 0; i < N - 1; ++i) {
if (mins[i] == INT_MAX) continue;
ans = max(ans, mins[i] - prev);
prev = maxes[i];
}
return max(ans, maxVal - prev);
}
};