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

"""
1. Counting sort - MLE
0 <= nums[i] <= 10^9
Boolean array of size 10**9 + 1 - MLE

2. Bucket sort
* Key idea:
    ** If n elements are divided into buckets of range (max-min)//n, then maximum difference between consecutive elements can be found as follows:
        *** Find min and max of each range
        *** Find difference between max of each range and min of next filled range
        *** The maximum of these differences is the answer
* Why does it work?
    ** What if maximum is within a range and not across buckets?
        *** This is impossible as the n elements have been distributed in to n buckets
            **** If a bucket contained more than one element, then automatically atleast one bucket would be empty
            **** This empty bucket would introduce more gap between two filled ranges
Source:
https://leetcode.com/problems/maximum-gap/solutions/1240543/python-bucket-sort-explained
"""
class Solution:
    def maximumGap(self, N: List[int]) -> int:
        N = list(set(N))        # [1,1,1,5,5,5]

        if len(N) == 1:         # [2]
            return 0

        def min_max(N):
            mn,mx = N[0],N[0]
            for n in N[1:]:
                mn,mx = min(mn,n),max(mx,n)
            return mn,mx

        lN = len(N)
        minN,maxN = min_max(N)
        diffN = (maxN-minN)
        if diffN == 0:          # [2,2,2]
            return 0
        if diffN >= lN:
            diffN = diffN//lN
        else:
            diffN = 1           # [5,6,7]

        R = [[] for _ in range(minN,maxN+1,diffN)]
        for n in N:
            i = (n-minN)//diffN
            R[i].append(n)

        R = [_ for _ in R if _]         # supress empty ranges
        R = [min_max(_) for _ in R]

        best = 0
        for (_,mx1),(mn2,_) in zip(R[:-1],R[1:]):
            best = max(best, abs(mn2-mx1))
        return best
42881