Very hard problem, if I didn't learn the algorithm first, I will never think of it. The idea is to divide the range max-min into some buckets. And assign all numbers to those buckets, then those numbers are already in order in the buckets. Finally scan the buckets and find out the maximum gap.
class Solution {
public:
int maximumGap(vector<int>& nums) {
if(nums.size()<2)
return 0;
int len=nums.size();
int Max=INT_MIN,Min=INT_MAX;
for(int i=0;i<len;i++)
{
if(nums[i]>Max)
Max=nums[i];
if(nums[i]<Min)
Min=nums[i];
}
int bsize=ceil((double)(Max-Min)/(len-1));//bucket size
int bnum=ceil((double)(Max-Min)/bsize)+1;//number of buckets
vector<pair<int,int> > buckets(bnum,make_pair(INT_MIN,INT_MAX));
for(int i=0;i<len;i++)
{
int idx=(nums[i]-Min)/bsize;//get the index of bucket this number should be
if(buckets[idx].first<nums[i])//update the max of the bucket
buckets[idx].first=nums[i];
if(buckets[idx].second>nums[i])//update the min of the bucket
buckets[idx].second=nums[i];
}
int res=INT_MIN,pre=0;
for(int curr=1;curr<buckets.size();curr++)
{
if(buckets[curr].first==INT_MIN)//empty bucket
continue;
res=max(res,buckets[curr].second-buckets[pre].first);
pre=curr;
}
return res;
}
};