Skip to content
Related Articles

Related Articles

Improve Article

Minimize replacements of leftmost largest array element required to make all array elements equal

  • Difficulty Level : Medium
  • Last Updated : 08 Jul, 2021
Geek Week

Given an array arr[] consisting of N integers, the task is to make all array elements equal by replacing the leftmost largest element of the array with the largest element strictly smaller than the current maximum minimum number of times.

Examples:

Input: arr[] = { 1, 1, 2, 2, 3<}
Output: 4
Explanation: Following operations reduces the required number of operations to minimum:

  1. Leftmost largest array element is arr[4]( = 3). Replacing it with the largest element smaller than the current largest, arr[3] (= 2), the array modifies to {1, 1, 2, 2, 2}.
  2. Leftmost largest element of the array is arr[2]( = 2). Replacing it with the largest element smaller than the current largest, arr[1] (= 1), the array modifies to {1, 1, 1, 2, 2}.
  3. Leftmost largest element of the array is arr[3]( = 2), replacing it with the largest element smaller than the current largest, arr[1] (= 1), the array modifies to {1, 1, 1, 1, 2}.
  4. Leftmost largest element of the array is arr[4]( = 2). Replacing it with the largest element smaller than the current largest, arr[1] (=1), the array modifies to {1, 1, 1, 1, 1}

Therefore, a minimum of 4 moves are needed.

Input: arr[] = {5, 1, 3
Output: 3

Approach: The problem can be solved by sort the array in descending order based on the observations that at each step, an array element will replace all the elements that are larger than the current array element. Follow the steps to solve the problem:



  • Sort the array in descending order.
  • Initialize a variable, say count as 0, to count the total number of moves required.
  • Iterate over the range [1, N – 1] using a variable i and perform the following steps: 
    • If arr[i] != arr[i – 1], then increment count by i.
  • Finally, after completing the above steps, the print value obtained in count as the answer.

Below is the implementation of the above approach:

C++




// C++ program for above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to count minimum number of
// times the leftmost larger element is
// required to be replaced to make
// all array elements equal
int reductionOperations(int arr[], int N)
{
    // Sort the array in descending order
    sort(arr, arr + N, greater<int>());
 
    // Stores minimum number of moves required
    int count = 0;
 
    // Traverse the array
    for (int i = 1; i < N; i++) {
 
        // If arr[i - 1] is not equal to arr[i]
        if (arr[i - 1] != arr[i]) {
 
            // Update count
            count += i;
        }
    }
 
    // Return count
    return count;
}
 
// Driver code
int main()
{
    // Given input
    int arr[] = { 1, 1, 2, 2, 3 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << reductionOperations(arr, N);
}

Java




// Java Program for the above approach
import java.io.*;
import java.util.Arrays;
class GFG {
    public static int reductionOperations(int arr[], int N)
    {
        // Sort the array in descending order
        Arrays.sort(arr);
        reverse(arr);
 
        // Stores minimum number of moves required
        int count = 0;
 
        // Traverse the array
        for (int i = 1; i < N; i++) {
 
            // If arr[i - 1] is not equal to arr[i]
            if (arr[i - 1] != arr[i]) {
 
                // Update count
                count += i;
            }
        }
 
        // Return count
        return count;
    }
 
    public static void reverse(int[] array)
    {
 
        // Length of the array
        int n = array.length;
 
        // Swaping the first half elements with last half
        // elements
        for (int i = 0; i < n / 2; i++) {
 
            // Storing the first half elements temporarily
            int temp = array[i];
 
            // Assigning the first half to the last half
            array[i] = array[n - i - 1];
 
            // Assigning the last half to the first half
            array[n - i - 1] = temp;
        }
    }
 
    public static void main(String[] args)
    {
        // Given input
        int arr[] = { 1, 1, 2, 2, 3 };
        int N = arr.length;
 
        // Function Call
        System.out.println(reductionOperations(arr, N));
    }
}
 
  // This code is contributed by Potta Lokesh

Python3




# python 3 program for above approach
 
# Function to count minimum number of
# times the leftmost larger element is
# required to be replaced to make
# all array elements equal
def reductionOperations(arr, N):
   
    # Sort the array in descending order
    arr.sort(reverse=True)
 
    # Stores minimum number of moves required
    count = 0
 
    # Traverse the array
    for i in range(1, N, 1):
       
        # If arr[i - 1] is not equal to arr[i]
        if (arr[i - 1] != arr[i]):
 
            # Update count
            count += i
 
    # Return count
    return count
 
# Driver code
if __name__ == '__main__':
   
    # Given input
    arr = [1, 1, 2, 2, 3]
    N = len(arr)
 
    # Function Call
    print(reductionOperations(arr, N))
     
    # This code is contributed by ipg2016107.

C#




// C# program for the above approach
using System;
 
class GFG{
     
static int reductionOperations(int[] arr, int N)
{
     
    // Sort the array in descending order
    Array.Sort(arr);
    reverse(arr);
 
    // Stores minimum number of moves required
    int count = 0;
 
    // Traverse the array
    for(int i = 1; i < N; i++)
    {
         
        // If arr[i - 1] is not equal to arr[i]
        if (arr[i - 1] != arr[i])
        {
             
            // Update count
            count += i;
        }
    }
     
    // Return count
    return count;
}
 
static void reverse(int[] array)
{
     
    // Length of the array
    int n = array.Length;
 
    // Swaping the first half elements
    // with last half elements
    for(int i = 0; i < n / 2; i++)
    {
         
        // Storing the first half
        // elements temporarily
        int temp = array[i];
 
        // Assigning the first half
        // to the last half
        array[i] = array[n - i - 1];
 
        // Assigning the last half
        // to the first half
        array[n - i - 1] = temp;
    }
}
 
// Driver code
public static void Main()
{
     
    // Given input
    int[] arr = { 1, 1, 2, 2, 3 };
    int N = arr.Length;
 
    // Function Call
    Console.Write(reductionOperations(arr, N));
}
}
 
// This code is contributed by subham348

Javascript




<script>
        // JavaScript program for the above approach
 
        // Function to count minimum number of
        // times the leftmost larger element is
        // required to be replaced to make
        // all array elements equal
        function reductionOperations(arr, N)
        {
         
            // Sort the array in descending order
            arr.sort(function (a, b) { return b - a });
             
            // Stores minimum number of moves required
            let count = 0;
 
            // Traverse the array
            for (let i = 1; i < N; i++) {
 
                // If arr[i - 1] is not equal to arr[i]
                if (arr[i - 1] != arr[i]) {
 
                    // Update count
                    count += i;
                }
            }
 
            // Return count
            return count;
        }
 
        // Driver code
 
        // Given input
        let arr = [1, 1, 2, 2, 3];
        let N = arr.length;
 
        // Function Call
        document.write(reductionOperations(arr, N));
 
  // This code is contributed by Potta Lokesh
    </script>
Output
4

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

 

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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :