<p>Given an integer array <code>nums</code>, return <em>the maximum difference between two successive elements in its sorted form</em>. If the array contains less than two elements, return <code>0</code>.</p>

<p>You must write an algorithm that runs in linear time and uses linear extra space.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [3,6,9,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [10]
<strong>Output:</strong> 0
<strong>Explanation:</strong> The array contains less than 2 elements, therefore return 0.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
	<li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>
</ul>

class Solution {
public:

    int findBucket(int num, int maxnum, int minnum, int n){
        int d=(maxnum-minnum+1)/(n-1);
        int nlarge=0;
        nlarge=(maxnum-minnum+1)%(n-1);
        // cout<<"d="<<d<<"\n";
        // cout<<"nlarge="<<nlarge<<"\n";
        int gap=num-minnum;
        if(gap<nlarge*(d+1)){
            return gap/(d+1);
        }
        return nlarge+(gap-nlarge*(d+1))/d;
    }

    int maximumGap(vector<int>& nums) {
        if(nums.size()<2) return 0;
        vector<vector<int>> bucket;
        vector<int> maxbucket;
        vector<int> minbucket;
        vector<int> sizebucket;
        int n=nums.size();
        for(int i=0;i<n-1;++i){
            maxbucket.push_back(-1);
            minbucket.push_back(1000000009);
            sizebucket.push_back(0);
        }
        int maxnum=-1;
        int minnum=1000000009;
        for(int num: nums){
            maxnum=max(maxnum, num);
            minnum=min(minnum, num);
        }
        if(maxnum==minnum) return 0;
        for(int num: nums){
            int bid=findBucket(num, maxnum, minnum, n);
            // cout<<"bid="<<bid<<"\n";
            minbucket[bid]=min(minbucket[bid], num);
            maxbucket[bid]=max(maxbucket[bid], num);
            sizebucket[bid]+=1;
        }
        int prev=-1;
        int ans=0;
        for(int i=0;i<n-1;++i){
            if(sizebucket[i]==0) continue;
            if(sizebucket[i]==2) ans=max(ans, maxbucket[i]-minbucket[i]);
            if(prev!=-1){
                ans=max(ans, minbucket[i]-maxbucket[prev]);
            }
            prev=i;
        }
        return ans;
    }
};
105388