Given an integer array nums
, return the maximum difference between two successive elements in its sorted form. If the array contains less than two elements, return 0
.
You must write an algorithm that runs in linear time and uses linear extra space.
Example 1:
Input: nums = [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.
Example 2:
Input: nums = [10] Output: 0 Explanation: The array contains less than 2 elements, therefore return 0.
Constraints:
1 <= nums.length <= 104
0 <= nums[i] <= 109
Companies:
Amazon
Related Topics:
Sort
// OJ: https://leetcode.com/problems/maximum-gap/
// Author: 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>& A) {
if (A.size() == 1) return 0;
int minVal = *min_element(begin(A), end(A));
int maxVal = *max_element(begin(A), end(A));
int N = A.size(), gap = (maxVal - minVal + N - 2) / (N - 1);
vector<int> mn(N - 1, INT_MAX), mx(N - 1, INT_MIN);
for (int n : A) {
if (n == minVal || n == maxVal) continue;
int i = (n - minVal) / gap;
mn[i] = min(mn[i], n);
mx[i] = max(mx[i], n);
}
int ans = gap, prev = minVal;
for (int i = 0; i < N - 1; ++i) {
if (mn[i] == INT_MAX) continue;
ans = max(ans, mn[i] - prev);
prev = mx[i];
}
return max(ans, maxVal - prev);
}
};