# 164. 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.

Example 1:

``````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.
``````

Example 2:

``````Input: [10]
Output: 0
Explanation: The array contains less than 2 elements, therefore return 0.
``````

Note:

• You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.
• Try to solve it in linear time/space.

``````class Solution {
public:
int maximumGap(vector<int>& nums) {
if (nums.size() <= 1) return 0;
int mx = INT_MIN, mn = INT_MAX, n = nums.size(), pre = 0, res = 0;
for (int num : nums) {
mx = max(mx, num);
mn = min(mn, num);
}
int size = (mx - mn) / n + 1, cnt = (mx - mn) / size + 1;
vector<int> bucket_min(cnt, INT_MAX), bucket_max(cnt, INT_MIN);
for (int num : nums) {
int idx = (num - mn) / size;
bucket_min[idx] = min(bucket_min[idx], num);
bucket_max[idx] = max(bucket_max[idx], num);
}
for (int i = 1; i < cnt; ++i) {
if (bucket_min[i] == INT_MAX || bucket_max[i] == INT_MIN) continue;
res = max(res, bucket_min[i] - bucket_max[pre]);
pre = i;
}
return res;
}
};
``````

Github 同步地址：

https://leetcode.com/problems/maximum-gap

http://blog.csdn.net/u011345136/article/details/41963051

https://leetcode.com/problems/maximum-gap/discuss/50643/bucket-sort-java-solution-with-explanation-on-time-and-space

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation