Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Minimum count of array elements that must be changed such that difference between maximum and minimum array element is N – 1

  • Difficulty Level : Easy
  • Last Updated : 27 Oct, 2021

Given an array arr[] consisting of N integers, the task is to find the minimum number of array elements that must be changed to any arbitrary integers such that the difference between maximum and minimum array element is (N – 1) and all array elements must be distinct.

Examples:

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[] = {1, 2, 3, 5, 6}
Output: 1
Explanation:
Change 6->4, the final array will be {1, 2, 3, 5, 4} and the difference is equal to 5 – 1 = 4.



Input: arr[] = {1, 10, 100, 1000}
Output: 3

 

Approach: The given problem can be solved by using the Sorting and Sliding Window Technique. Follow the steps below to solve the problem:

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the minimum changes
// needed to make difference of maximum
// and minimum element as (N - 1)
int minOperations(vector<int>& A)
{
    int N = A.size();
 
    // Stores the resultant count
    int ans = N;
 
    // Maintain a pointer j that will
    // denote the rightmost position of
    // the valid array
    int j = 0;
 
    // Sort the array
    sort(begin(A), end(A));
 
    // Only keep unique elements
    A.erase(unique(begin(A), end(A)),
            end(A));
 
    // Store the new size of the array
    // after removing duplicates
    int M = A.size();
   
    // IterM;ate over the range
    for (int i = 0; i < M; ++i) {
        while (j < M && A[j] <= A[i] + N - 1) {
            ++j;
        }
 
        // Check minimum over this
        // starting point
        ans = min(ans, N - j + i);
 
        // The length of this subarray
        // is `j - i`. Replace `N - j + i`
        // elements to make it good
    }
 
    return ans;
}
 
// Driver Code
int main()
{
    vector<int> arr = { 1, 10, 100, 1000 };
    cout << minOperations(arr);
 
    return 0;
}

Java




// Java program for the above approach
import java.util.Arrays;
import java.util.*;
 
class GFG {
 
    // Function to find the minimum changes
    // needed to make difference of maximum
    // and minimum element as (N - 1)
    public static int minOperations(int[] A) {
        int N = A.length;
 
        // Stores the resultant count
        int ans = N;
 
        // Maintain a pointer j that will
        // denote the rightmost position of
        // the valid array
        int j = 0;
 
        // Sort the array
        Arrays.sort(A);
 
        // Only keep unique elements
        removeDups(A);
 
        // Store the new size of the array
        // after removing duplicates
        int M = A.length;
 
        // IterM;ate over the range
        for (int i = 0; i < M; ++i) {
            while (j < M && A[j] <= A[i] + N - 1) {
                ++j;
            }
 
            // Check minimum over this
            // starting point
            ans = Math.min(ans, N - j + i);
 
            // The length of this subarray
            // is `j - i`. Replace `N - j + i`
            // elements to make it good
        }
 
        return ans;
    }
 
    public static void removeDups(int[] a) {
 
        LinkedHashSet<Integer> set = new LinkedHashSet<Integer>();
 
        // adding elements to LinkedHashSet
        for (int i = 0; i < a.length; i++)
            set.add(a[i]);
 
    }
 
    // Driver Code
    public static void main(String args[]) {
        int[] arr = { 1, 10, 100, 1000 };
        System.out.println(minOperations(arr));
 
    }
 
}
 
// This code is contributed by saurabh_jaiswal.

Python3




# Python 3 program for the above approach
 
# Function to find the minimum changes
# needed to make difference of maximum
# and minimum element as (N - 1)
def minOperations(A):
    N = len(A)
 
    # Stores the resultant count
    ans = N
 
    # Maintain a pointer j that will
    # denote the rightmost position of
    # the valid array
    j = 0
 
    # Sort the array
    A.sort()
 
    # Only keep unique elements
    A = list(set(A))
 
    # Store the new size of the array
    # after removing duplicates
    A.sort()
    M = len(A)
   
    # IterM;ate over the range
    for i in range(M):
        while (j < M and A[j] <= A[i] + N - 1):
            j += 1
 
        # Check minimum over this
        # starting point
        ans = min(ans, N - j + i)
 
        # The length of this subarray
        # is `j - i`. Replace `N - j + i`
        # elements to make it good
 
    return ans
 
# Driver Code
if __name__ == '__main__':
    arr = [1, 10, 100, 1000]
    print(minOperations(arr))
     
    # This code is contributed by ipg2016107.

C#




// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG {
 
    // Function to find the minimum changes
    // needed to make difference of maximum
    // and minimum element as (N - 1)
    public static int minOperations(int[] A) {
        int N = A.Length;
 
        // Stores the resultant count
        int ans = N;
 
        // Maintain a pointer j that will
        // denote the rightmost position of
        // the valid array
        int j = 0;
 
        // Sort the array
        Array.Sort(A);
 
        // Only keep unique elements
        removeDups(A);
 
        // Store the new size of the array
        // after removing duplicates
        int M = A.Length;
 
        // IterM;ate over the range
        for (int i = 0; i < M; ++i) {
            while (j < M && A[j] <= A[i] + N - 1) {
                ++j;
            }
 
            // Check minimum over this
            // starting point
            ans = Math.Min(ans, N - j + i);
 
            // The length of this subarray
            // is `j - i`. Replace `N - j + i`
            // elements to make it good
        }
 
        return ans;
    }
 
    public static void removeDups(int[] a) {
 
        HashSet<int> set = new HashSet<int>();
 
        // adding elements to LinkedHashSet
        for (int i = 0; i < a.Length; i++)
            set.Add(a[i]);
 
    }
 
    // Driver Code
    public static void Main() {
        int[] arr = { 1, 10, 100, 1000 };
        Console.Write(minOperations(arr));
    }
 
}
 
// This code is contributed by saurabh_jaiswal.

Javascript




<script>
       // JavaScript Program to implement
       // the above approach
 
       // Function to find the minimum changes
       // needed to make difference of maximum
       // and minimum element as (N - 1)
       function minOperations(A)
       {
           let N = A.length;
 
           // Stores the resultant count
           let ans = N;
 
           // Maintain a pointer j that will
           // denote the rightmost position of
           // the valid array
           let j = 0;
 
           // Sort the array
           A.sort(function (a, b) { return a - b });
 
           // Only keep unique elements
           let unique_A = [];
           for (let i = 0; i < A.length - 1; i++) {
               if (A[i] != A[i + 1]) {
                   unique_A.push(A[i])
               }
           }
           A = unique_A;
           // Store the new size of the array
           // after removing duplicates
           let M = A.length;
 
           // Iterate over the range
           for (let i = 0; i < M; ++i) {
               while (j < M && A[j] <= A[i] + N - 1) {
                   ++j;
               }
 
               // Check minimum over this
               // starting point
               ans = Math.min(ans, N - j + i);
 
               // The length of this subarray
               // is `j - i`. Replace `N - j + i`
               // elements to make it good
           }
 
           return ans;
       }
 
       // Driver Code
 
       let arr = [1, 10, 100, 1000];
       document.write(minOperations(arr));
 
    // This code is contributed by Potta Lokesh
   </script>
Output: 
3

 

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




My Personal Notes arrow_drop_up
Recommended Articles
Page :