Problem Summary
Given an unsorted array of N integers, find the maximum difference between the successive elements in its sorted form.
Solution 1: O(NlogN) time
Sort the array with quick sort, merge sort or heap sort. Then iterate through the array.
Solution 2: O(N) time
We know that bucket sort only takes O(N) time to allocate the numbers to buckets. If we make sure that the size of each bucket is small enough, we can save us the trouble of gathering the numbers from buckets.
Actually, once we notice that the lower limit of the answer is L = (max - min)/(N-1), we can set the bucket size to ceil(L) (L rounds up to ceil(l)). Then the maximum difference between numbers in one bucket is at most ceil(L)-1, which is smaller than the answer we want. So we only need to consider the differences of numbers in different buckets. To implement this, we can iterate through each non-empty buckets, and for two adjacent non-empty buckets A and B, we update the answer with the difference between the minimum in B and the maximum in A, i.e. min(B) - max(A).
Code
|
|