![]() |
VOOZH | about |
Given an array arr[] of size N, find the maximum difference between its two consecutive elements in its sorted form.
Examples:
Input: N = 3, arr[] = {1, 10, 5}
Output: 5
Explanation: Sorted array would be {1, 5, 10} and maximum adjacent difference would be 10 - 5 = 5Input: N = 4, arr[] = {2, 4, 8, 11}
Output: 4
Explanation: Sorted array would be {2, 4, 8, 11} and the maximum adjacent difference would be 8 - 4 = 4
Naive Solution:
First sort the array, then traverse it and keep track of the maximum difference between adjacent elements.
The time complexity of this method is O(nlogn).
Efficient Solution:
This solution is based on the idea of Pigeonhole sorting. No need to sort the array, just have to fill the buckets and keep track of the maximum and minimum value of each bucket. If found an empty bucket, The maximum gap would be the difference of maximum value in theprevious bucket - minimum value in thenext bucket.
As we want to almost sort these so that, we can have maximum gap. Also, for any ith element, the value of (arr[i]-min_value)/(max_value-min_value) keeps increasing as arr[i] keeps increasing and this value always varies from 0 to 1. As we want to put the sorted results in bucket of size n. We multiply this value by (n-1) hence make a variable delta = (max_value - min_value)/(n-1). Now in maxBucket or minBucket, all the value at any index j before index any i will always less than the value at index i, minBucket[j]<minBucket[i] for j<i. It is possible that two different arr[i], might have same value of (arr[i]-min_value)/delta, therefore we are making 2 different buckets maxBucket and minBucket.
As we have find the max difference between consecutive values, we must consider the max possible value upto to previous index as prev_val and the minBucket[i] for current index i, and ans will be max of ans and minBucket[i]-prev_val.
Let us solve the above example by this approach.
Working Example:
Input: arr[] = {1, 10, 5}
Output: 5
Step1: Find max_val and min_val
max_val = 10, min_val = 1
Step2: Calculate delta
delta = (max_val - min_val)/(n-1)
delta = (10-1)/(3-1) = 4.5
Step3: Initialize buckets, maxBucket={INT_MIN}, minBucket={INT_MAX}
Step4: For any index i, calculate index arr[i] in bucket and update in buckets,
in = (arr[i]-min_val)/delta
maxBucket[in]=max(maxBucket[in],arr[i])
minBucket[in]=min(minBucket[in],arr[i])
for all index in arr in values are => 0,2,0
maxBucket=[5,INT_MIN,10]
minBucket=[1,INT_MAX,10]
Step5: Hence ans is max of minBucket[i]-(max of value upto previous index)
in this case for i=2: max_gap = max(max_gap,minBucket[2] - max(maxBucket[1],maxBucket[0]))
max_gap = 10-5=5
This is just for presenting the concept, all other basic validations are in the main code.
Below is the code for the above approach:
5
Time complexity: O(N)
Auxiliary Space: O(N)