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 <= 105
0 <= nums[i] <= 109
Solutions
Solution 1: Bucket Sort
Thinking
Maximum gap after sorting, in linear time. Comparison sorts are \(O(n \log n)\); \(n\le 10^5\). The max adjacent gap is at least \((\textit{max}-\textit{min})/(n-1)\). Bucket by that width: gaps inside a bucket are smaller than this lower bound, so the answer is between consecutive non-empty buckets (next min minus previous max). Each bucket stores only min and max.
Suppose \(\textit{nums}\) has \(n\) elements. After sorting them into \(\textit{nums}_0 \le \cdots \le \textit{nums}_{n-1}\), the maximum adjacent gap \(\textit{maxGap}\) satisfies
Use that lower bound as the bucket width, and at least \(1\) when every value is equal. Values that fall in the same bucket differ by less than \(\textit{maxGap}\), so a gap of size \(\textit{maxGap}\) always crosses two buckets. Each bucket keeps only its minimum and its maximum, initialized to \(+\infty\) and \(-\infty\) to mark an empty bucket.
Place every value \(v\) into bucket \(\lfloor(v - \min) / \textit{bucketSize}\rfloor\). Smaller indices then hold smaller values. Scan the buckets from left to right. The minimum of the current non-empty bucket and the maximum of the previous non-empty bucket are adjacent in sorted order; their difference updates the answer. There is no gap before the first non-empty bucket.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\), where \(n\) is the length of \(\textit{nums}\).