Skip to content
Related Articles

Related Articles

Maximum adjacent difference in an array in its sorted form
  • Difficulty Level : Hard
  • Last Updated : 20 Jan, 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.
Below is the code for the above approach:

C++




// 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);
 
        // 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.
    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




// Java program for the above approach
import 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




# 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 Code
if __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#




// 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 Code
public static void Main()
{
    int []arr = {1, 10, 5};
    int n = arr.Length;
    Console.Write(maxSortedAdjacentDiff(arr, n));
}
}
 
// This code contributed by 29AjayKumar
Output: 
5

 

Time complexity: O(n) 
Auxiliary Space: O(n)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :