Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Minimize difference between maximum and minimum element of all possible subarrays

  • Difficulty Level : Basic
  • Last Updated : 10 Sep, 2021

Given an array arr[ ] of size N, the task is to find the minimum difference between maximum and minimum elements of all possible sized subarrays of arr[ ].
  
 Examples: 

Input: arr[] = { 5, 14, 7, 10 }  
Output: 3
Explanation: {7, 10} is the subarray having max element = 10 & min element = 7, and their difference = 10 – 7 = 3

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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: arr[] = { 2, 6, 15, 7, 6 }  
Output: 1  
Explanation: {7, 6} is the subarray having max element = 7 & min element = 6, and their difference = 7 – 6 = 1



 

 
Approach:  The simple idea is to use two loops and check for every subarray, the minimum difference between the maximum and the minimum element. Keep track of the differences and return the minimum possible difference. Time Complexity for this approach would be Quadratic.

Efficient Approach:  The idea is to use the fact that we can get minimum difference by iterating over only the subarrays of size two.
Suppose we have two elements in our subarray. Let the difference between maximum and minimum element be x. Now if we include an element from either the right side or left side to our subarray, the maximum element or minimum element might get updated. This change will ultimately make our difference x increase, as either max or min element is getting updated.

Follow the below steps to implement the above approach:

  • Iterate the array and keep track of the minimum adjacent difference
  • Print this min difference as the result.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to get the min difference
// between max and min element of all
// possible subarrays
int getMinDifference(int arr[], int n)
{
    // To store the adjacent difference
    int diff;
 
    // To compare with min difference
    int mn = INT_MAX;
 
    for (int i = 1; i < n; i++) {
 
        // Storing adjacent difference
        diff = abs(arr[i] - arr[i - 1]);
 
        // Updating the min difference
        mn = min(diff, mn);
    }
 
    // Returning min difference
    return mn;
}
 
// Driver code
int main()
{
 
    int arr[] = { 2, 6, 15, 7, 6 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << getMinDifference(arr, N);
    return 0;
}

Java




// Java program for the above approach
import java.io.*;
 
class GFG{
 
// Function to get the min difference
// between max and min element of all
// possible subarrays
static int getMinDifference(int []arr, int n)
{
    // To store the adjacent difference
    int diff = 0;
 
    // To compare with min difference
    int mn = Integer.MAX_VALUE;
 
    for (int i = 1; i < n; i++) {
 
        // Storing adjacent difference
        diff = Math.abs(arr[i] - arr[i - 1]);
 
        // Updating the min difference
        mn = Math.min(diff, mn);
    }
 
    // Returning min difference
    return mn;
}
 
// Driver code
public static void main (String[] args)
{
 
    int []arr = {2, 6, 15, 7, 6 };
    int N = arr.length;
    System.out.println(getMinDifference(arr, N));
}
}
 
// This code is contributed by shivanisinghss2110

Python3




# Python3 program for the above approach
import sys,math
 
# Function to get the min difference
# between max and min element of all
# possible subarrays
def getMinDifference(arr, n) :
 
    INT_MAX = sys.maxsize;
     
    # To compare with min difference
    mn = INT_MAX;
 
    for i in range(1, n):
 
        # Storing adjacent difference
        diff = abs(arr[i] - arr[i - 1]);
 
        # Updating the min difference
        mn = min(diff, mn);
 
    # Returning min difference
    return mn;
 
# Driver code
if __name__ == "__main__" :
 
 
    arr = [ 2, 6, 15, 7, 6 ];
    N = len(arr);
    print(getMinDifference(arr, N));
 
    # This code is contributed by AnkThon

C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to get the min difference
// between max and min element of all
// possible subarrays
static int getMinDifference(int []arr, int n)
{
    // To store the adjacent difference
    int diff = 0;
 
    // To compare with min difference
    int mn = Int32.MaxValue;
 
    for (int i = 1; i < n; i++) {
 
        // Storing adjacent difference
        diff = Math.Abs(arr[i] - arr[i - 1]);
 
        // Updating the min difference
        mn = Math.Min(diff, mn);
    }
 
    // Returning min difference
    return mn;
}
 
// Driver code
public static void Main()
{
 
    int []arr = {2, 6, 15, 7, 6 };
    int N = arr.Length;
    Console.Write(getMinDifference(arr, N));
}
}
 
// This code is contributed by SURENDRA_GANGWAR.

Javascript




<script>
        // JavaScript Program to implement
        // the above approach
 
 
        // Function to get the min difference
        // between max and min element of all
        // possible subarrays
        function getMinDifference(arr, n) {
            // To store the adjacent difference
            let diff;
 
            // To compare with min difference
            let mn = Number.MAX_VALUE;
 
            for (let i = 1; i < n; i++) {
 
                // Storing adjacent difference
                diff = Math.abs(arr[i] - arr[i - 1]);
 
                // Updating the min difference
                mn = Math.min(diff, mn);
            }
 
            // Returning min difference
            return mn;
        }
 
        // Driver code
 
        let arr = [2, 6, 15, 7, 6];
        let N = arr.length;
        document.write(getMinDifference(arr, N));
 
// This code is contributed by Potta Lokesh
 
    </script>
Output
1

Time Complexity: O(N), N is the number of elements
Auxiliary Space: O(1)
 




My Personal Notes arrow_drop_up
Recommended Articles
Page :