Minimize adding odd and subtracting even numbers to make all array elements equal to K

Given an array, arr[] of size N and an integer K, the task is to find the minimum number of operations required to make all array elements equal to K by performing the following operations any number of times:
- Convert arr[i] to arr[i] + X, where X is an odd number.
- Convert arr[i] to arr[i] – Y, where Y is an even number.
Examples:
Input: arr[] = {8, 7, 2, 1, 3}, K = 5Â
Output: 8Â
Explanation: To make all elements of the given array equal to K(= 5), following operations are required:Â
arr[0] = arr[0] + X, X = 1Â
arr[0] = arr[0] – Y, Y = 4Â
arr[1] = arr[1] – Y, Y = 2Â
arr[2] = arr[2] + X, X = 3Â
arr[3] = arr[3] + X, X = 3Â
arr[3] = arr[3] + X, X = 1Â
arr[4] = arr[4] + X, X = 1Â
arr[4] = arr[4] + X, X = 1Input: arr[] = {1, 2, 3, 4, 5, 6, 7}, K = 3Â
Output: 9Â
Â
Approach: The problem can be solved using the Greedy technique. Following are the observations:
Even + Even = EvenÂ
Even + Odd = OddÂ
Odd + Odd = EvenÂ
Odd + Even = OddÂ
Follow the steps below to solve the problem:
- Traverse the given array and check the following conditions.Â
- If K > arr[i] and (K – arr[i]) % 2 == 0 then add two odd numbers(X) into arr[i]. Therefore, total 2 operations required.
- If K > arr[i] and (K – arr[i]) % 2 != 0 then add one odd numbers(X) into arr[i]. Therefore, total 1 operations required.
- If K < arr[i] and (arr[i] – arr[i]) % 2 == 0 then subtract one even numbers(Y) into arr[i]. Therefore, total 1 operations required.
- If K < arr[i] and (K – arr[i]) % 2 != 0 then add an odd numbers(X) into arr[i] and subtract an even numbers(Y) from arr[i]. Therefore, total 2 operations required.
- Finally, print the total number of operations required to make all the array elements equal to K.
Below is the implementation of the above approach
C++
// C++ program to implement// the above approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to find the minimum operations// required to make array elements equal to Kint MinOperation(int arr[], int N, int K){    // Stores minimum count of operations    int cntOpe = 0;Â
    // Traverse the given array    for (int i = 0; i < N; i++) {Â
        // If K is greater than arr[i]        if (K > arr[i]) {Â
            // If (K - arr[i]) is even            if ((K - arr[i]) % 2 == 0) {Â
                // Update cntOpe                cntOpe += 2;            }            else {Â
                // Update cntOpe                cntOpe += 1;            }        }Â
        // If K is less than arr[i]        else if (K < arr[i]) {Â
            // If (arr[i] - K) is even            if ((K - arr[i]) % 2 == 0) {Â
                // Update cntOpe                cntOpe += 1;            }            else {Â
                // Update cntOpe                cntOpe += 2;            }        }    }Â
    return cntOpe;}Â
// Driver Codeint main(){Â Â Â Â int arr[] = { 8, 7, 2, 1, 3 };Â Â Â Â int K = 5;Â Â Â Â int N = sizeof(arr) / sizeof(arr[0]);Â Â Â Â cout << MinOperation(arr, N, K);Â
    return 0;} |
Java
// Java program to implement // the above approach class GFG{     // Function to find the minimum // operations required to make // array elements equal to K public static int MinOperation(int arr[],                                int N, int K) {   // Stores minimum count of   // operations   int cntOpe = 0; Â
  // Traverse the given array   for (int i = 0; i < N; i++)   {    // If K is greater than    // arr[i]     if (K > arr[i])     {      // If (K - arr[i]) is even       if ((K - arr[i]) % 2 == 0)       {        // Update cntOpe         cntOpe += 2;       }       else      {        // Update cntOpe         cntOpe += 1;       }     } Â
    // If K is less than     // arr[i]     else if (K < arr[i])     {      // If (arr[i] - K) is       // even       if ((K - arr[i]) % 2 == 0)       {        // Update cntOpe         cntOpe += 1;       }       else      {        // Update cntOpe         cntOpe += 2;       }     }   } Â
  return cntOpe; } Â
// Driver codepublic static void main(String[] args) {Â Â int arr[] = {8, 7, 2, 1, 3}; Â Â int K = 5; Â Â int N = arr.length; Â Â System.out.println(Â Â MinOperation(arr, N, K));}}Â
// This code is contributed by divyeshrabadiya07 |
Python3
# Python3 program to implement# the above approach  # Function to find the minimum operations# required to make array elements equal to Kdef MinOperation(arr, N, K):         # Stores minimum count of operations    cntOpe = 0      # Traverse the given array    for i in range(N):          # If K is greater than arr[i]        if (K > arr[i]):              # If (K - arr[i]) is even            if ((K - arr[i]) % 2 == 0):                  # Update cntOpe                cntOpe += 2                         else:                  # Update cntOpe                cntOpe += 1                     # If K is less than arr[i]        elif (K < arr[i]):                         # If (arr[i] - K) is even            if ((K - arr[i]) % 2 == 0):                  # Update cntOpe                cntOpe += 1                         else:                  # Update cntOpe                cntOpe += 2Â
    return cntOpeÂ
# Driver Codearr = [ 8, 7, 2, 1, 3 ]K = 5N = len(arr)Â
print(MinOperation(arr, N, K))Â
# This code is contributed by sanjoy_62 |
C#
// C# program to implement // the above approach using System;Â
class GFG{     // Function to find the minimum // operations required to make // array elements equal to K public static int MinOperation(int []arr,                                int N, int K) {      // Stores minimum count of   // operations   int cntOpe = 0; Â
  // Traverse the given array   for(int i = 0; i < N; i++)   {         // If K is greater than    // arr[i]     if (K > arr[i])     {             // If (K - arr[i]) is even       if ((K - arr[i]) % 2 == 0)       {                 // Update cntOpe         cntOpe += 2;       }       else      {                 // Update cntOpe         cntOpe += 1;       }     } Â
    // If K is less than     // arr[i]     else if (K < arr[i])     {             // If (arr[i] - K) is       // even       if ((K - arr[i]) % 2 == 0)       {                 // Update cntOpe         cntOpe += 1;       }       else      {                 // Update cntOpe         cntOpe += 2;       }     }   }   return cntOpe; } Â
// Driver codepublic static void Main(String[] args) {Â Â int []arr = {8, 7, 2, 1, 3}; Â Â int K = 5; Â Â int N = arr.Length;Â Â Â Â Â Console.WriteLine(Â Â MinOperation(arr, N, K));}}Â
// This code is contributed by Amit Katiyar |
Javascript
<script>// Javascript program to implement// the above approachÂ
// Function to find the minimum// operations required to make// array elements equal to Kfunction MinOperation(arr, N, K){  // Stores minimum count of  // operations  let cntOpe = 0;    // Traverse the given array  for (let i = 0; i < N; i++)  {    // If K is greater than    // arr[i]    if (K > arr[i])    {      // If (K - arr[i]) is even      if ((K - arr[i]) % 2 == 0)      {        // Update cntOpe        cntOpe += 2;      }      else      {        // Update cntOpe        cntOpe += 1;      }    }      // If K is less than    // arr[i]    else if (K < arr[i])    {      // If (arr[i] - K) is      // even      if ((K - arr[i]) % 2 == 0)      {        // Update cntOpe        cntOpe += 1;      }      else      {        // Update cntOpe        cntOpe += 2;      }    }  }    return cntOpe;}Â
    // Driver Code         let arr = [8, 7, 2, 1, 3];  let K = 5;  let N = arr.length;  document.write(  MinOperation(arr, N, K));      </script> |
8
Â
Time Complexity: O(N)
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



