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 maximum difference between any pair of array elements by exactly one removal
Next article icon

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

Last Updated : 18 May, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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 = 3
Output: 2
Explanation:
Remove elements 12, 10 and 1 from the given array.
The array modifies to {5, 6, 7}.
The difference between the minimum and maximum element is 7 – 5 = 2.

Input: arr[] = {14, 5, 61, 10, 21, 12, 54}, K = 4
Output: 4
Explanation:
Remove elements 61, 54, 5 and 21 from the given array.
The array modifies to {14, 10, 12}.
The difference between the minimum and maximum element is 14 – 10 = 4.

Approach: The idea to solve the given problem is that the difference will be minimized by removing either the minimum element in an array or the maximum element in the array. Follow the steps below to solve the problem:

  • Sort the array arr[] in ascending order.
  • Initialize variables left = 0 and right = (N – 1).
  • Iterate for K times and change the maximum or minimum to 0 according to the following condition:
    • If arr[right – 1] – arr[left] < arr[right] – arr[left + 1], then change arr[right] to 0 and decrement right pointer by 1.
    • Else, change arr[left] as 0 and increment the left pointer by 1.
  • After the above steps, the difference between the elements at the left and right index is the required minimum difference.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
 
// Function to minimize the difference
// of the maximum and minimum array
// elements by removing K elements
void minimumRange(int arr[], int N, int K)
{
    // Base Condition
    if (K >= N)
    {
        cout << 0;
        return;
    }
 
    // Sort the array
    sort(arr, arr + N);
 
    // Initialize left and right pointers
    int left = 0, right = N - 1, i;
 
    // Iterate for K times
    for (i = 0; i < K; i++)
    {
 
        // Removing right element
        // to reduce the difference
        if (arr[right - 1] - arr[left]
            < arr[right] - arr[left + 1])
            right--;
 
        // Removing the left element
        // to reduce the difference
        else
            left++;
    }
 
    // Print the minimum difference
    cout << arr[right] - arr[left];
}
 
// Driver Code
int main()
{
    int arr[] = { 5, 10, 12, 14, 21, 54, 61 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    int K = 4;
 
    // Function Call
    minimumRange(arr, N, K);
 
    return 0;
}
 
 

Java




// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to minimize the difference
// of the maximum and minimum array
// elements by removing K elements
static void minimumRange(int arr[], int N,
                         int K)
{
     
    // Base Condition
    if (K >= N)
    {
        System.out.print(0);
        return;
    }
     
    // Sort the array
    Arrays.sort(arr);
     
    // Initialize left and right pointers
    int left = 0, right = N - 1, i;
 
    // Iterate for K times
    for(i = 0; i < K; i++)
    {
         
        // Removing right element
        // to reduce the difference
        if (arr[right - 1] - arr[left] <
            arr[right] - arr[left + 1])
            right--;
             
        // Removing the left element
        // to reduce the difference
        else
            left++;
    }
     
    // Print the minimum difference
    System.out.print(arr[right] - arr[left]);
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 5, 10, 12, 14, 21, 54, 61 };
    int N = arr.length;
    int K = 4;
 
    // Function Call
    minimumRange(arr, N, K);
}
}
 
// This code is contributed by 29AjayKumar
 
 

Python3




# Python3 program for the above approach
 
# Function to minimize the difference
# of the maximum and minimum array
# elements by removing K elements
def minimumRange(arr, N, K) :
 
    # Base Condition
    if (K >= N) :
        print(0, end = '');
        return;
 
    # Sort the array
    arr.sort();
 
    # Initialize left and right pointers
    left = 0; right = N - 1;
 
    # Iterate for K times
    for i in range(K) :
 
        # Removing right element
        # to reduce the difference
        if (arr[right - 1] - arr[left] < arr[right] - arr[left + 1]) :
            right -= 1;
 
        # Removing the left element
        # to reduce the difference
        else :
            left += 1;
 
    # Print the minimum difference
    print(arr[right] - arr[left], end = '');
 
# Driver Code
if __name__ == "__main__" :
 
    arr = [ 5, 10, 12, 14, 21, 54, 61 ];
    N = len(arr);
 
    K = 4;
 
    # Function Call
    minimumRange(arr, N, K);
 
    # This code is contributed by AnkitRai01
 
 

C#




// C# program for the above approach
using System;
class GFG{
 
// Function to minimize the difference
// of the maximum and minimum array
// elements by removing K elements
static void minimumRange(int []arr, int N,
                         int K)
{
     
    // Base Condition
    if (K >= N)
    {
        Console.Write(0);
        return;
    }
     
    // Sort the array
    Array.Sort(arr);
     
    // Initialize left and right pointers
    int left = 0, right = N - 1, i;
 
    // Iterate for K times
    for(i = 0; i < K; i++)
    {
         
        // Removing right element
        // to reduce the difference
        if (arr[right - 1] - arr[left] <
            arr[right] - arr[left + 1])
            right--;
             
        // Removing the left element
        // to reduce the difference
        else
            left++;
    }
     
    // Print the minimum difference
    Console.Write(arr[right] - arr[left]);
}
 
// Driver Code
public static void Main(String[] args)
{
    int []arr = { 5, 10, 12, 14, 21, 54, 61 };
    int N = arr.Length;
    int K = 4;
 
    // Function Call
    minimumRange(arr, N, K);
}
}
 
// This code is contributed by 29AjayKumar
 
 

Javascript




<script>
 
// JavaScript program for the above approach
 
// Function to minimize the difference
// of the maximum and minimum array
// elements by removing K elements
function minimumRange(arr, N, K)
{
    // Base Condition
    if (K >= N)
    {
        document.write( 0);
        return;
    }
 
    // Sort the array
    arr.sort((a,b)=> a-b);
 
    // Initialize left and right pointers
    var left = 0, right = N - 1, i;
 
    // Iterate for K times
    for (i = 0; i < K; i++)
    {
 
        // Removing right element
        // to reduce the difference
        if (arr[right - 1] - arr[left]
            < arr[right] - arr[left + 1])
            right--;
 
        // Removing the left element
        // to reduce the difference
        else
            left++;
    }
 
    // Print the minimum difference
    document.write( arr[right] - arr[left]);
}
 
// Driver Code
var arr = [5, 10, 12, 14, 21, 54, 61];
var N = arr.length;
var K = 4;
 
// Function Call
minimumRange(arr, N, K);
 
</script>
 
 
Output: 
4

 

Time Complexity: O(N*log N)
Auxiliary Space: O(1)



Next Article
Minimize maximum difference between any pair of array elements by exactly one removal

M

ManikantaBandla
Improve
Article Tags :
  • Arrays
  • DSA
  • Greedy
  • Mathematical
  • Sorting
  • array-rearrange
  • two-pointer-algorithm
Practice Tags :
  • Arrays
  • Greedy
  • Mathematical
  • Sorting
  • two-pointer-algorithm

Similar Reads

  • 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
  • Minimize difference between maximum and minimum array elements by removing a K-length subarray
    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 = 2Output: 4Explanation: Remove the subarray {
    10 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
  • Minimize maximum difference between adjacent elements possible by removing a single array element
    Given an sorted array arr[] consisting of N elements, the task is to find the minimum of all maximum differences between adjacent elements of all arrays obtained by removal of any single array element. Examples: Input: arr[ ] = { 1, 3, 7, 8}Output: 5Explanation:All possible arrays after removing a s
    6 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
  • Split array into minimum number of subsets having difference between maximum and minimum element at most K
    Given an array arr[] consisting of N integers and an integer K, the task is to find the minimum number of sets, the array elements can be divided into such that the difference between the maximum and minimum element of each set is at most K. Examples: Input: arr[] = {1, 2, 3, 4, 5}, K = 2 Output: 2E
    6 min read
  • Minimize difference between the largest and smallest array elements by K replacements
    Given an array A[] consisting of N integers, the task is to find the minimum difference between the largest and the smallest element in the given array after replacing K elements. Examples: Input: A[] = {-1, 3, -1, 8, 5, 4}, K = 3Output: 2Explanation:Replace A[0] and A[2] by 3 and 4 respectively. Re
    12 min read
  • Minimize difference between maximum and minimum element by decreasing and increasing Array elements by 1
    Given an array arr[], consisting of N positive integers. The task is to minimize the difference between the maximum and the minimum element of the array by performing the below operation any number of times (possibly zero). In one operation choose 2 different index, i and j and decrement arr[i] and
    5 min read
  • Maximize minimum array element possible by exactly K decrements
    Given an array arr[] consisting of N integers and an integer K, the task is to maximize the minimum element of the array after decrementing array elements exactly K number of times. Examples: Input: arr[] = {2, 4, 4}, K = 3 Output: 2Explanation:One of the possible way is: Decrement arr[2] by 1. The
    7 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