Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Minimize difference between maximum and minimum array elements by exactly K removals
Next article icon

Minimize difference between maximum and minimum array elements by removing a K-length subarray

Last Updated : 13 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] consisting of N integers and an integer K, the task is to find the minimum difference between the maximum and minimum element present in the array after removing any subarray of size K.

Examples:

Input: arr[] = {4, 5, 8, 9, 1, 2}, K = 2
Output: 4
Explanation: Remove the subarray {8, 9}. The minimum difference between maximum and minimum array elements becomes (5 – 1) = 4.

Input: arr[] = {1, 2, 2}, K = 1
Output: 0
Explanation: Remove subarray {1}. The minimum difference between maximum and minimum array elements becomes (2 – 2) = 0.

 


Naive Approach: The simplest approach is to remove all possible subarrays of size K one by one and calculate the difference between maximum and minimum among the remaining elements. Finally, print the minimum difference obtained.
Time Complexity: O(N2)
Auxiliary Space: O(1)

Efficient Approach: The above approach can be optimized by storing maximum and minimum prefixes upto any index and storing the maximum and minimum suffixes starting from any index. Once the above four values are calculated, find the maximum and minimum array elements after removing a K-length subarray in constant computational complexity. 

Follow the steps below to solve the problem:

  • Initialize arrays maxSufix[] and minSuffix[]. such that ith element of maxSuffix[] and minSuffix[] array denotes the maximum and minimum elements respectively present at the right of the ith index.
  • Initialize two variables, say maxPrefix and minPrefix, to store the maximum and minimum elements present in the prefix subarray.
  • Traverse the array over the indices [1, N] and check if i + K <= N or not. If found to be true, then perform the following steps:
    • The maximum value present in the array after removing a subarray of size K starting from ith index is max(maxSuffix[i + k], maxPrefix).
    • The minimum value present in the array after removing a subarray of size K starting from ith index is min(minSuffix[i + k], minPrefix).
    • Update minDiff to min( minDiff, maximum – minimum), to store the minimum difference.
  • Print minDiff as the required answer.

Below is the implementation of the above approach:

C++

// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to minimize difference
// between maximum and minimum array
// elements by removing a K-length subarray
void minimiseDifference(vector<int>& arr, int K)
{
    // Size of array
    int N = arr.size();
 
    // Stores the maximum and minimum
    // in the suffix subarray [i .. N-1]
    int maxSuffix[N + 1], minSuffix[N + 1];
 
    maxSuffix[N] = -1e9;
    minSuffix[N] = 1e9;
    maxSuffix[N - 1] = arr[N - 1];
    minSuffix[N - 1] = arr[N - 1];
 
    // Constructing the maxSuffix and
    // minSuffix arrays
 
    // Traverse the array
    for (int i = N - 2; i >= 0; --i) {
 
        maxSuffix[i] = max(
maxSuffix[i + 1],
 arr[i]);
        minSuffix[i] = min(
minSuffix[i + 1],
 arr[i]);
    }
 
    // Stores the maximum and minimum
    // in the prefix subarray [0 .. i-1]
    int maxPrefix = arr[0];
    int minPrefix = arr[0];
 
    // Store the minimum difference
    int minDiff = maxSuffix[K] - minSuffix[K];
 
    // Traverse the array
    for (int i = 1; i < N; ++i) {
 
        // If the suffix doesn't exceed
        // the end of the array
        if (i + K <= N) {
 
            // Store the maximum element
            // in array after removing
            // subarray of size K
            int maximum = max(maxSuffix[i + K], maxPrefix);
 
            // Stores the maximum element
            // in array after removing
            // subarray of size K
            int minimum = min(minSuffix[i + K], minPrefix);
 
            // Update minimum difference
            minDiff = min(minDiff, maximum - minimum);
        }
 
        // Updating the maxPrefix and
        // minPrefix with current element
        maxPrefix = max(maxPrefix, arr[i]);
        minPrefix = min(minPrefix, arr[i]);
    }
 
    // Print the minimum difference
    cout << minDiff << "\n";
}
 
// Driver Code
int main()
{
    vector<int> arr = { 4, 5, 8, 9, 1, 2 };
    int K = 2;
    minimiseDifference(arr, K);
 
    return 0;
}
                      
                       

Java

// Java program for the above approach
import java.util.*;
class GFG
{
 
  // Function to minimize difference
  // between maximum and minimum array
  // elements by removing a K-length subarray
  static void minimiseDifference(int[] arr, int K)
  {
    // Size of array
    int N = arr.length;
 
    // Stores the maximum and minimum
    // in the suffix subarray [i .. N-1]
    int[] maxSuffix = new int[N + 1];
    int[] minSuffix = new int[N + 1];
 
    maxSuffix[N] = -1000000000;
    minSuffix[N] = 1000000000;
    maxSuffix[N - 1] = arr[N - 1];
    minSuffix[N - 1] = arr[N - 1];
 
    // Constructing the maxSuffix and
    // minSuffix arrays
 
    // Traverse the array
    for (int i = N - 2; i >= 0; --i) {
 
      maxSuffix[i]
        = Math.max(maxSuffix[i + 1], arr[i]);
      minSuffix[i]
        = Math.min(minSuffix[i + 1], arr[i]);
    }
 
    // Stores the maximum and minimum
    // in the prefix subarray [0 .. i-1]
    int maxPrefix = arr[0];
    int minPrefix = arr[0];
 
    // Store the minimum difference
    int minDiff = maxSuffix[K] - minSuffix[K];
 
    // Traverse the array
    for (int i = 1; i < N; ++i) {
 
      // If the suffix doesn't exceed
      // the end of the array
      if (i + K <= N) {
 
        // Store the maximum element
        // in array after removing
        // subarray of size K
        int maximum
          = Math.max(maxSuffix[i + K], maxPrefix);
 
        // Stores the maximum element
        // in array after removing
        // subarray of size K
        int minimum
          = Math.min(minSuffix[i + K], minPrefix);
 
        // Update minimum difference
        minDiff
          = Math.min(minDiff, maximum - minimum);
      }
 
      // Updating the maxPrefix and
      // minPrefix with current element
      maxPrefix = Math.max(maxPrefix, arr[i]);
      minPrefix = Math.min(minPrefix, arr[i]);
    }
 
    // Print the minimum difference
    System.out.print(minDiff);
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    int[] arr = { 4, 5, 8, 9, 1, 2 };
    int K = 2;
    minimiseDifference(arr, K);
  }
}
 
// This code is contributed by susmitakundugoaldanga.
                      
                       

Python3

# Python 3 program for the above approach
 
# Function to minimize difference
# between maximum and minimum array
# elements by removing a K-length subarray
def minimiseDifference(arr, K):
   
    # Size of array
    N = len(arr)
 
    # Stores the maximum and minimum
    # in the suffix subarray [i .. N-1]
    maxSuffix = [0 for i in range(N + 1)]
    minSuffix = [0 for i in range(N + 1)]
 
    maxSuffix[N] = -1e9
    minSuffix[N] = 1e9
    maxSuffix[N - 1] = arr[N - 1]
    minSuffix[N - 1] = arr[N - 1]
 
    # Constructing the maxSuffix and
    # minSuffix arrays
 
    # Traverse the array
    i = N - 2
    while(i >= 0):
        maxSuffix[i] = max(maxSuffix[i + 1],arr[i])
        minSuffix[i] = min(minSuffix[i + 1], arr[i])
        i -= 1
 
    # Stores the maximum and minimum
    # in the prefix subarray [0 .. i-1]
    maxPrefix = arr[0]
    minPrefix = arr[0]
 
    # Store the minimum difference
    minDiff = maxSuffix[K] - minSuffix[K]
 
    # Traverse the array
    for i in range(1, N):
       
        # If the suffix doesn't exceed
        # the end of the array
        if (i + K <= N):
           
            # Store the maximum element
            # in array after removing
            # subarray of size K
            maximum = max(maxSuffix[i + K], maxPrefix)
 
            # Stores the maximum element
            # in array after removing
            # subarray of size K
            minimum = min(minSuffix[i + K], minPrefix)
 
            # Update minimum difference
            minDiff = min(minDiff, maximum - minimum)
 
        # Updating the maxPrefix and
        # minPrefix with current element
        maxPrefix = max(maxPrefix, arr[i])
        minPrefix = min(minPrefix, arr[i])
 
    # Print the minimum difference
    print(minDiff)
 
# Driver Code
if __name__ == '__main__':
    arr =  [4, 5, 8, 9, 1, 2]
    K = 2
    minimiseDifference(arr, K)
     
    # This code is contributed by SURENDRA_GANGWAR.
                      
                       

C#

// C# program for the above approach
using System;
using System.Collections.Generic;
class GFg {
 
  // Function to minimize difference
  // between maximum and minimum array
  // elements by removing a K-length subarray
  static void minimiseDifference(List<int> arr, int K)
  {
    // Size of array
    int N = arr.Count;
 
    // Stores the maximum and minimum
    // in the suffix subarray [i .. N-1]
    int[] maxSuffix = new int[N + 1];
    int[] minSuffix = new int[N + 1];
 
    maxSuffix[N] = -1000000000;
    minSuffix[N] = 1000000000;
    maxSuffix[N - 1] = arr[N - 1];
    minSuffix[N - 1] = arr[N - 1];
 
    // Constructing the maxSuffix and
    // minSuffix arrays
 
    // Traverse the array
    for (int i = N - 2; i >= 0; --i) {
 
      maxSuffix[i]
        = Math.Max(maxSuffix[i + 1], arr[i]);
      minSuffix[i]
        = Math.Min(minSuffix[i + 1], arr[i]);
    }
 
    // Stores the maximum and minimum
    // in the prefix subarray [0 .. i-1]
    int maxPrefix = arr[0];
    int minPrefix = arr[0];
 
    // Store the minimum difference
    int minDiff = maxSuffix[K] - minSuffix[K];
 
    // Traverse the array
    for (int i = 1; i < N; ++i) {
 
      // If the suffix doesn't exceed
      // the end of the array
      if (i + K <= N) {
 
        // Store the maximum element
        // in array after removing
        // subarray of size K
        int maximum
          = Math.Max(maxSuffix[i + K], maxPrefix);
 
        // Stores the maximum element
        // in array after removing
        // subarray of size K
        int minimum
          = Math.Min(minSuffix[i + K], minPrefix);
 
        // Update minimum difference
        minDiff
          = Math.Min(minDiff, maximum - minimum);
      }
 
      // Updating the maxPrefix and
      // minPrefix with current element
      maxPrefix = Math.Max(maxPrefix, arr[i]);
      minPrefix = Math.Min(minPrefix, arr[i]);
    }
 
    // Print the minimum difference
    Console.WriteLine(minDiff);
  }
 
  // Driver Code
  public static void Main()
  {
    List<int> arr
      = new List<int>() { 4, 5, 8, 9, 1, 2 };
    int K = 2;
    minimiseDifference(arr, K);
  }
}
 
// This code is contributed by chitranayal.
                      
                       

Javascript

<script>
 
// JavaScript  program for the above approach
 
// Function to minimize difference
// between maximum and minimum array
// elements by removing a K-length subarray
function minimiseDifference(arr, K)
{
    // Size of array
    var N = arr.length;
 
    // Stores the maximum and minimum
    // in the suffix subarray [i .. N-1]
    var maxSuffix = new Array(N + 1);
    var minSuffix = new Array(N + 1);
 
    maxSuffix[N] = -1e9;
    minSuffix[N] = 1e9;
    maxSuffix[N - 1] = arr[N - 1];
    minSuffix[N - 1] = arr[N - 1];
 
    // Constructing the maxSuffix and
    // minSuffix arrays
 
    // Traverse the array
    for (var i = N - 2; i >= 0; --i) {
 
        maxSuffix[i] = Math.max(maxSuffix[i + 1], arr[i]);
        minSuffix[i] = Math.min(minSuffix[i + 1], arr[i]);
    }
 
    // Stores the maximum and minimum
    // in the prefix subarray [0 .. i-1]
    var maxPrefix = arr[0];
    var minPrefix = arr[0];
 
    // Store the minimum difference
    var minDiff = maxSuffix[K] - minSuffix[K];
 
    // Traverse the array
    for (var i = 1; i < N; ++i) {
 
        // If the suffix doesn't exceed
        // the end of the array
        if (i + K <= N) {
 
            // Store the maximum element
            // in array after removing
            // subarray of size K
            var maximum =
            Math.max(maxSuffix[i + K], maxPrefix);
 
            // Stores the maximum element
            // in array after removing
            // subarray of size K
            var minimum =
            Math.min(minSuffix[i + K], minPrefix);
 
            // Update minimum difference
            minDiff =
            Math.min(minDiff, maximum - minimum);
        }
 
        // Updating the maxPrefix and
        // minPrefix with current element
        maxPrefix = Math.max(maxPrefix, arr[i]);
        minPrefix = Math.min(minPrefix, arr[i]);
    }
 
    // Print the minimum difference
   document.write( minDiff + "<br>");
}
 
 
var arr = [ 4, 5, 8, 9, 1, 2 ];
var K = 2;
minimiseDifference(arr, K);
 
// This code is contributed by SoumikMondal
 
</script>
                      
                       

 
 


Output
4


Time Complexity: O(N)
Auxiliary Space: O(N) 

Related Topic: Subarrays, Subsequences, and Subsets in Array



Next Article
Minimize difference between maximum and minimum array elements by exactly K removals

S

shreyasshetty788
Improve
Article Tags :
  • Arrays
  • DSA
  • Mathematical
  • Searching
  • array-rearrange
  • prefix
  • subarray
  • Suffix
Practice Tags :
  • Arrays
  • Mathematical
  • Searching

Similar Reads

  • Minimize difference between maximum and minimum array elements by exactly K removals
    Given an array arr[] consisting of N positive integers and an integer K, the task is to minimize the difference between the maximum and minimum element in the given array after removing exactly K elements. Examples: Input: arr[] = {5, 1, 6, 7, 12, 10}, K = 3Output: 2Explanation:Remove elements 12, 1
    6 min read
  • Minimize difference between maximum and minimum element of all possible subarrays
    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: 3Explanation: {7, 10} is the subarray having max element = 10 & min element = 7, and their
    5 min read
  • Minimize maximum difference between any pair of array elements by exactly one removal
    Given an array arr[] consisting of N integers(N > 2), the task is to minimize the maximum difference between any pair of elements (arr[i], arr[j]) by removing exactly one element. Examples: Input: arr[] = {1, 3, 4, 7}Output: 3Explanation:Removing the element 7 from array, modifies the array to {1
    9 min read
  • Split a given array into K subarrays minimizing the difference between their maximum and minimum
    Given a sorted array arr[] of N integers and an integer K, the task is to split the array into K subarrays such that the sum of the difference of maximum and minimum element of each subarray is minimized. Examples: Input: arr[] = {1, 3, 3, 7}, K = 4 Output: 0 Explanation: The given array can be spli
    6 min read
  • Minimize the difference between minimum and maximum elements
    Given an array of [Tex]N [/Tex]integers and an integer [Tex]k [/Tex]. It is allowed to modify an element either by increasing or decreasing them by k (only once).The task is to minimize and print the maximum difference between the shortest and longest towers. Examples: Input: arr[] = {1, 10, 8, 5},
    8 min read
  • Minimize sum of differences between maximum and minimum elements present in K subsets
    Given an array arr[] of size N and an integer K, the task is to minimize the sum of the difference between the maximum and minimum element of each subset by splitting the array into K subsets such that each subset consists of unique array elements only. Examples: Input: arr[] = { 6, 3, 8, 1, 3, 1, 2
    12 min read
  • Difference between maximum and minimum average of all K-length contiguous subarrays
    Given an array arr[] of size N and an integer K, the task is to print the difference between the maximum and minimum average of the contiguous subarrays of length K. Examples: Input: arr[ ] = {3, 8, 9, 15}, K = 2Output: 6.5Explanation:All subarrays of length 2 are {3, 8}, {8, 9}, {9, 15} and their a
    11 min read
  • Minimum distance between the maximum and minimum element of a given Array
    Given an array A[] consisting of N elements, the task is to find the minimum distance between the minimum and the maximum element of the array.Examples: Input: arr[] = {3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 8, 2} Output: 3 Explanation: The minimum element(= 1) is present at indices {2, 4} The maximum elemen
    8 min read
  • Minimize count of Subsets with difference between maximum and minimum element not exceeding K
    Given an array arr[ ] and an integer K, the task is to split the given array into minimum number of subsets having the difference between the maximum and the minimum element ≤ K. Examples: Input: arr[ ] = {1, 3, 7, 9, 10}, K = 3Output: 2Explanation:One of the possible subsets of arr[] are {1, 3} and
    5 min read
  • Maximize the minimum difference between any element pair by selecting K elements from given Array
    Given an array of N integers the task is to select K elements out of these N elements in such a way that the minimum difference between each of the K numbers is the Largest. Return the largest minimum difference after choosing any K elements. Examples: Input: N = 4, K = 3, arr = [2, 6, 2, 5]Output:
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences