Maximum adjacent difference in an array in its sorted form - GeeksforGeeks

24 Jun, 2021
Given an array, find the maximum difference between its two consecutive elements in its sorted form.Examples: 
Input: arr[] = {1, 10, 5}
Output: 5
Sorted array would be {1, 5, 10} and
maximum adjacent difference would be 
10 - 5 = 5

Input: arr[] = {2, 4, 8, 11}
Output: 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 the previous bucket – minimum value in the next 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:
C++
Java
Python3
C#
Javascript
// CPP program to find maximum adjacent difference// between two adjacent after sorting.#include <bits/stdc++.h>using namespace std; int maxSortedAdjacentDiff(int* arr, int n){    // Find maximum and minimum in arr[]    int maxVal = arr[0], minVal = arr[0];    for (int i = 1; i < n; i++) {        maxVal = max(maxVal, arr[i]);        minVal = min(minVal, arr[i]);    }     // Arrays to store maximum and minimum values    // in n-1 buckets of differences.    int maxBucket[n - 1];    int minBucket[n - 1];    fill_n(maxBucket, n - 1, INT_MIN);    fill_n(minBucket, n - 1, INT_MAX);     // Expected gap for every bucket.    float delta = (float)(maxVal - minVal) / (float)(n - 1);     // Traversing through array elements and    // filling in appropriate bucket if bucket    // is empty. Else updating bucket values.    for (int i = 0; i < n; i++) {        if (arr[i] == maxVal || arr[i] == minVal)            continue;         // Finding index of bucket.        int index = (float)(floor(arr[i] - minVal) / delta);         maxBucket[index] = max(maxBucket[index], arr[i]);           minBucket[index] = min(minBucket[index], arr[i]);    }     // Finding maximum difference between maximum value    // of previous bucket minus minimum of current bucket.    int prev_val = minVal;    int max_gap = 0;    for (int i = 0; i < n - 1; i++) {        if (minBucket[i] == INT_MAX)            continue;        max_gap = max(max_gap, minBucket[i] - prev_val);        prev_val = maxBucket[i];    }    max_gap = max(max_gap, maxVal - prev_val);     return max_gap;} int main(){    int arr[] = { 1, 10, 5 };    int n = sizeof(arr) / sizeof(arr[0]);    cout << maxSortedAdjacentDiff(arr, n) << endl;    return 0;}
// Java program for the above approachimport java.util.Arrays; // Java program to find maximum adjacent difference// between two adjacent after sorting.class GFG {     static int maxSortedAdjacentDiff(int[] arr, int n)    {        // Find maximum and minimum in arr[]        int maxVal = arr[0];        int minVal = arr[0];        for (int i = 1; i < n; i++) {            maxVal = Math.max(maxVal, arr[i]);            minVal = Math.min(minVal, arr[i]);        }         // Arrays to store maximum and minimum values        // in n-1 buckets of differences.        int maxBucket[] = new int[n - 1];        int minBucket[] = new int[n - 1];        Arrays.fill(maxBucket, 0, n - 1, Integer.MIN_VALUE);        Arrays.fill(minBucket, 0, n - 1, Integer.MAX_VALUE);         // Expected gap for every bucket.        float delta            = (float)(maxVal - minVal) / (float)(n - 1);         // Traversing through array elements and        // filling in appropriate bucket if bucket        // is empty. Else updating bucket values.        for (int i = 0; i < n; i++) {            if (arr[i] == maxVal || arr[i] == minVal) {                continue;            }             // Finding index of bucket.            int index = (int)(Math.round((arr[i] - minVal)                                         / delta));             // Filling/Updating maximum value of bucket            if (maxBucket[index] == Integer.MIN_VALUE) {                maxBucket[index] = arr[i];            }            else {                maxBucket[index]                    = Math.max(maxBucket[index], arr[i]);            }             // Filling/Updating minimum value of bucket            if (minBucket[index] == Integer.MAX_VALUE) {                minBucket[index] = arr[i];            }            else {                minBucket[index]                    = Math.min(minBucket[index], arr[i]);            }        }         // Finding maximum difference between maximum value        // of previous bucket minus minimum of current        // bucket.        int prev_val = minVal;        int max_gap = 0;        for (int i = 0; i < n - 1; i++) {            if (minBucket[i] == Integer.MAX_VALUE) {                continue;            }            max_gap = Math.max(max_gap,                               minBucket[i] - prev_val);            prev_val = maxBucket[i];        }        max_gap = Math.max(max_gap, maxVal - prev_val);         return max_gap;    }     // Driver program to run the case    public static void main(String[] args)    {         int arr[] = { 1, 10, 5 };        int n = arr.length;        System.out.println(maxSortedAdjacentDiff(arr, n));    }}
# Python3 program to find maximum adjacent# difference between two adjacent after sorting. def maxSortedAdjacentDiff(arr, n):     # Find maximum and minimum in arr[]    maxVal, minVal = arr[0], arr[0]    for i in range(1, n):        maxVal = max(maxVal, arr[i])        minVal = min(minVal, arr[i])     # Arrays to store maximum and minimum    # values in n-1 buckets of differences.    maxBucket = [INT_MIN] * (n - 1)    minBucket = [INT_MAX] * (n - 1)         # Expected gap for every bucket.    delta = (maxVal - minVal) // (n - 1)     # Traversing through array elements and    # filling in appropriate bucket if bucket    # is empty. Else updating bucket values.    for i in range(0, n):        if arr[i] == maxVal or arr[i] == minVal:            continue         # Finding index of bucket.        index = (arr[i] - minVal) // delta         # Filling/Updating maximum value        # of bucket        if maxBucket[index] == INT_MIN:            maxBucket[index] = arr[i]        else:            maxBucket[index] = max(maxBucket[index],                                             arr[i])         # Filling/Updating minimum value of bucket        if minBucket[index] == INT_MAX:            minBucket[index] = arr[i]        else:            minBucket[index] = min(minBucket[index],                                             arr[i])         # Finding maximum difference between     # maximum value of previous bucket    # minus minimum of current bucket.    prev_val, max_gap = minVal, 0         for i in range(0, n - 1):        if minBucket[i] == INT_MAX:            continue                     max_gap = max(max_gap,                      minBucket[i] - prev_val)        prev_val = maxBucket[i]         max_gap = max(max_gap, maxVal - prev_val)     return max_gap # Driver Codeif __name__ == "__main__":     arr = [1, 10, 5]    n = len(arr)    INT_MIN, INT_MAX = float('-inf'), float('inf')         print(maxSortedAdjacentDiff(arr, n)) # This code is contributed by Rituraj Jain
// C# program to find maximum// adjacent difference between// two adjacent after sorting.using System;using System.Linq; class GFG{static int maxSortedAdjacentDiff(int[] arr,                                     int n){    // Find maximum and minimum in arr[]    int maxVal = arr[0];    int minVal = arr[0];    for (int i = 1; i < n; i++)    {        maxVal = Math.Max(maxVal, arr[i]);        minVal = Math.Min(minVal, arr[i]);    }     // Arrays to store maximum and    // minimum values in n-1 buckets    // of differences.    int []maxBucket = new int[n - 1];    int []minBucket = new int[n - 1];    maxBucket = maxBucket.Select(i => int.MinValue).ToArray();    minBucket = minBucket.Select(i => int.MaxValue).ToArray();         // maxBucket.Fill(int.MinValue);    // Arrays.fill(minBucket, 0, n - 1, Integer.MAX_VALUE);     // Expected gap for every bucket.    float delta = (float) (maxVal - minVal) /                  (float) (n - 1);     // Traversing through array elements and    // filling in appropriate bucket if bucket    // is empty. Else updating bucket values.    for (int i = 0; i < n; i++)    {        if (arr[i] == maxVal || arr[i] == minVal)        {            continue;        }         // Finding index of bucket.        int index = (int) (Math.Round((arr[i] -                             minVal) / delta));         // Filling/Updating maximum value of bucket        if (maxBucket[index] == int.MinValue)        {            maxBucket[index] = arr[i];        }        else        {            maxBucket[index] = Math.Max(maxBucket[index],                                                  arr[i]);        }         // Filling/Updating minimum value of bucket        if (minBucket[index] == int.MaxValue)        {            minBucket[index] = arr[i];        }        else        {            minBucket[index] = Math.Min(minBucket[index],                                                  arr[i]);        }    }     // Finding maximum difference between    // maximum value of previous bucket    // minus minimum of current bucket.    int prev_val = minVal;    int max_gap = 0;    for (int i = 0; i < n - 1; i++)    {        if (minBucket[i] == int.MaxValue)        {            continue;        }        max_gap = Math.Max(max_gap, minBucket[i] -                                    prev_val);        prev_val = maxBucket[i];    }    max_gap = Math.Max(max_gap, maxVal -                                prev_val);     return max_gap;} // Driver Codepublic static void Main(){    int []arr = {1, 10, 5};    int n = arr.Length;    Console.Write(maxSortedAdjacentDiff(arr, n));}} // This code contributed by 29AjayKumar
<script> // JavaScript program to find maximum adjacent difference// between two adjacent after sorting. function maxSortedAdjacentDiff(arr, n){    // Find maximum and minimum in arr[]    var maxVal = arr[0], minVal = arr[0];    for (var i = 1; i < n; i++) {        maxVal = Math.max(maxVal, arr[i]);        minVal = Math.min(minVal, arr[i]);    }     // Arrays to store maximum and minimum values    // in n-1 buckets of differences.    var maxBucket = Array(n-1).fill(-1000000000);    var minBucket = Array(n-1).fill(1000000000);     // Expected gap for every bucket.    var delta = (maxVal - minVal) / (n - 1);     // Traversing through array elements and    // filling in appropriate bucket if bucket    // is empty. Else updating bucket values.    for (var i = 0; i < n; i++) {        if (arr[i] == maxVal || arr[i] == minVal)            continue;         // Finding index of bucket.        var index = Math.floor((arr[i] - minVal) / delta);         maxBucket[index] = Math.max(maxBucket[index], arr[i]);           minBucket[index] = Math.min(minBucket[index], arr[i]);    }     // Finding maximum difference between maximum value    // of previous bucket minus minimum of current bucket.    var prev_val = minVal;    var max_gap = 0;    for (var i = 0; i < n - 1; i++) {        if (minBucket[i] == 1000000000)            continue;        max_gap = Math.max(max_gap, minBucket[i] - prev_val);        prev_val = maxBucket[i];    }    max_gap = Math.max(max_gap, maxVal - prev_val);     return max_gap;} var arr = [1, 10, 5];var n = arr.length;document.write( maxSortedAdjacentDiff(arr, n));  </script>
5
Time complexity: O(n) Auxiliary Space: O(n)
Rajput-Ji
29AjayKumar
rituraj_jain
nehal sharma
2701gouravgoel
rrrtnx
khushboogoyal499
Pigeonhole Principle
Arrays
Searching
Arrays
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Python | Using 2D arrays/lists the right way
Maximum and minimum of an array using minimum number of comparisons
Find the Missing Number
K'th Smallest/Largest Element in Unsorted Array | Set 1
Program to find largest element in an array
Search an element in a sorted and rotated array