Minimum increment/decrement operations required to make Median as X

Given an array A[] of n odd integers and an integer X. Calculate the minimum number of operations required to make the median of the array equal to X, where, in one operation we can either increase or decrease any single element by one.
Examples:Â
Input: A[] = {6, 5, 8}, X = 8Â
Output: 2Â
Explanation:Â
Here 6 can be increased twice. The array will become 8, 5, 8, which becomes 5, 8, 8 after sorting, hence the median is equal to 8.Input: A[] = {1, 4, 7, 12, 3, 5, 9}, X = 5Â
Output: 0Â
Explanation:Â
After sorting 5 is in middle position hence 0 steps are required.Â
Â
Approach: The idea for changing the median of the array will be to sort the given array. Then after sorting, the best possible candidate for making the median is the middle element because it will be better to reduce the numbers before the middle element as they are smaller and increase the numbers after the middle element as they are larger.
Below is the implementation of the above approach:Â Â
C++
// C++ implementation to determine the // Minimum numbers of steps to make // median of an array equal X Â
#include <bits/stdc++.h> using namespace std; Â
// Function to count minimum // required operations to // make median X int count(vector<int> a, int X) { Â Â Â Â // Sorting the array a[] Â Â Â Â sort(a.begin(), a.end()); Â Â Â Â int ans = 0; Â
    // Calculate the size of array     int n = a.size(); Â
    // Iterate over the array     for (int i = 0; i < n; i++) {         // For all elements         // less than median         if (i < n / 2)             ans += max(0, a[i] - X); Â
        // For element equal         // to median         else if (i == n / 2)             ans += abs(X - a[i]); Â
        // For all elements         // greater than median         else            ans += max(0, X - a[i]);     } Â
    // Return the answer     return ans; } Â
// Driver code int main() { Â Â Â Â vector<int> a = { 6, 5, 8 }; Â Â Â Â int X = 8; Â Â Â Â cout << count(a, X) << "\n"; Â Â Â Â return 0; } |
Java
// Java implementation to determine the// Minimum numbers of steps to make// median of an array equal Ximport java.util.*;Â
class GFG{Â
// Function to count minimum// required operations to// make median Xstatic int count(int[] a, int X){Â Â Â Â Â Â Â Â Â // Sorting the array a[]Â Â Â Â Arrays.sort(a);Â Â Â Â int ans = 0;Â
    // Calculate the size of array    int n = a.length;Â
    // Iterate over the array    for(int i = 0; i < n; i++)    {               // For all elements       // less than median       if (i < n / 2)           ans += Math.max(0, a[i] - X);               // For element equal       // to median       else if (i == n / 2)           ans += Math.abs(X - a[i]);              // For all elements       // greater than median       else           ans += Math.max(0, X - a[i]);    }         // Return the answer    return ans;}Â
// Driver codepublic static void main(String[] args){Â Â Â Â int []a = { 6, 5, 8 };Â Â Â Â int X = 8;Â Â Â Â Â Â Â Â Â System.out.print(count(a, X) + "\n");}}Â
// This code is contributed by Amit Katiyar |
Python3
# Python3 implementation to determine the # Minimum numbers of steps to make # median of an array equal X Â
# Function to count minimum # required operations to # make median X def count(a, X): Â
    # Sorting the array a[]     a.sort()    ans = 0Â
    # Calculate the size of array     n = len(a)Â
    # Iterate over the array     for i in range(n):                 # For all elements         # less than median         if (i < n // 2):             ans += max(0, a[i] - X)Â
        # For element equal         # to median         elif (i == n // 2):             ans += abs(X - a[i]) Â
        # For all elements         # greater than median         else:            ans += max(0, X - a[i]); Â
    # Return the answer     return ansÂ
# Driver codea = [ 6, 5, 8 ] X = 8Â
print(count(a, X)) Â
# This code is contributed by divyeshrabadiya07 |
C#
// C# implementation to determine the// Minimum numbers of steps to make// median of an array equal Xusing System;Â
class GFG{Â
// Function to count minimum// required operations to// make median Xstatic int count(int[] a, int X){         // Sorting the array []a    Array.Sort(a);    int ans = 0;Â
    // Calculate the size of array    int n = a.Length;Â
    // Iterate over the array    for(int i = 0; i < n; i++)    {               // For all elements       // less than median       if (i < n / 2)           ans += Math.Max(0, a[i] - X);                   // For element equal       // to median       else if (i == n / 2)           ans += Math.Abs(X - a[i]);               // For all elements       // greater than median       else           ans += Math.Max(0, X - a[i]);    }         // Return the answer    return ans;}Â
// Driver codepublic static void Main(String[] args){Â Â Â Â int []a = { 6, 5, 8 };Â Â Â Â int X = 8;Â Â Â Â Â Â Â Â Â Console.Write(count(a, X) + "\n");}}Â
// This code is contributed by Amit Katiyar |
Javascript
<script>Â
// Javascript implementation to determine the// Minimum numbers of steps to make// median of an array equal XÂ
// Creating the bblSort functionfunction bblSort(arr){    for(var i = 0; i < arr.length; i++)    {             // Last i elements are already in place         for(var j = 0; j < (arr.length - i - 1); j++)        {                     // Checking if the item at present            // iteration is greater than the             // next iteration            if (arr[j] > arr[j+1])            {                             // If the condition is true                // then swap them                var temp = arr[j]                arr[j] = arr[j + 1]                arr[j + 1] = temp            }        }    }         // Return the sorted array    return (arr);}Â
// Function to count minimum// required operations to// make median Xfunction count(a, X){         // Sorting the array a    a = bblSort(a);    var ans = 0;Â
    // Calculate the size of array    var n = a.length;Â
    // Iterate over the array    for(i = 0; i < n; i++)     {                 // For all elements        // less than median        if (i < parseInt(n / 2))            ans += Math.max(0, a[i] - X);Â
        // For element equal        // to median        else if (i == parseInt(n / 2))            ans += Math.abs(X - a[i]);Â
        // For all elements        // greater than median        else            ans += Math.max(0, X - a[i]);    }         // Return the answer    return ans;}Â
// Driver codevar a = [ 6, 5, 8 ];var X = 8;Â
document.write(count(a, X));Â
// This code is contributed by aashish1995Â
</script> |
2
Â
Time Complexity: O(N * log N)
Auxiliary Space Complexity: O(1)
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



