Open In App

Make all array elements equal with minimum cost

Last Updated : 22 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array of size n, the task is to make the value of all elements equal with minimum cost. The cost of changing a value from x to y is abs(x – y).

Examples : 

Input: arr[] = [1, 100, 101]
Output: 100
Explanation: We can change all its values to 100 with minimum cost,
|1 – 100| + |100 – 100| + |101 – 100| = 100

Input: arr[] = [4, 6]
Output: 2
Explanation: We can change all its values to 5 with minimum cost,
|4 – 5| + |5 – 6| = 2

Input: arr[] = [5, 5, 5, 5]
Output: 0
Explanation: All the values are already equal.

[Naive Approach] Using 2 Nested Loops – O(n^2) time and O(1) space

Please note that our answer can always be one of the array values. Even in the second example above, we can alternatively make both as 4 or both as 6 at the same cost..
The idea is to consider each value in the array as a potential target value, then calculate the total cost of converting all other elements to that target value. By checking all possible target values, we can find the one that results in the minimum overall cost of conversion.

C++
// C++ program to Make all array 
// elements equal with minimum cost
#include <bits/stdc++.h>
using namespace std;

// Function which finds the minimum 
// cost to make array elements equal
int minCost(vector<int> &arr) {
    int n = arr.size();
    int ans = INT_MAX;
    
    // Try each element as the target value
    for (int i = 0; i < n; i++) {
        int currentCost = 0;
        
        // Calculate cost of making all 
        // elements equal to arr[i]
        for (int j = 0; j < n; j++) {
            currentCost += abs(arr[j] - arr[i]);
        }
        
        // Update minimum cost if current cost is lower
        ans = min(ans, currentCost);
    }
    
    return ans;
}

int main() {
    vector<int> arr = {1, 100, 101};
    cout << minCost(arr) << endl;
    
    return 0;
}
Java
// Java program to Make all array 
// elements equal with minimum cost
import java.util.*;

class GfG {

    // Function which finds the minimum 
    // cost to make array elements equal
    static int minCost(int[] arr) {
        int n = arr.length;
        int ans = Integer.MAX_VALUE;

        // Try each element as the target value
        for (int i = 0; i < n; i++) {
            int currentCost = 0;

            // Calculate cost of making all 
            // elements equal to arr[i]
            for (int j = 0; j < n; j++) {
                currentCost += Math.abs(arr[j] - arr[i]);
            }

            // Update minimum cost if current cost is lower
            ans = Math.min(ans, currentCost);
        }

        return ans;
    }

    public static void main(String[] args) {
        int[] arr = {1, 100, 101};
        System.out.println(minCost(arr));
    }
}
Python
# Python program to Make all array 
# elements equal with minimum cost

# Function which finds the minimum 
# cost to make array elements equal
def minCost(arr):
    n = len(arr)
    ans = float('inf')

    # Try each element as the target value
    for i in range(n):
        currentCost = 0

        # Calculate cost of making all 
        # elements equal to arr[i]
        for j in range(n):
            currentCost += abs(arr[j] - arr[i])

        # Update minimum cost if current cost is lower
        ans = min(ans, currentCost)

    return ans

if __name__ == "__main__":
    arr = [1, 100, 101]
    print(minCost(arr))
C#
// C# program to Make all array 
// elements equal with minimum cost
using System;

class GfG {

    // Function which finds the minimum 
    // cost to make array elements equal
    static int minCost(int[] arr) {
        int n = arr.Length;
        int ans = int.MaxValue;

        // Try each element as the target value
        for (int i = 0; i < n; i++) {
            int currentCost = 0;

            // Calculate cost of making all 
            // elements equal to arr[i]
            for (int j = 0; j < n; j++) {
                currentCost += Math.Abs(arr[j] - arr[i]);
            }

            // Update minimum cost if current cost is lower
            ans = Math.Min(ans, currentCost);
        }

        return ans;
    }

    static void Main() {
        int[] arr = {1, 100, 101};
        Console.WriteLine(minCost(arr));
    }
}
JavaScript
// JavaScript program to Make all array 
// elements equal with minimum cost

// Function which finds the minimum 
// cost to make array elements equal
function minCost(arr) {
    let n = arr.length;
    let ans = Number.MAX_SAFE_INTEGER;

    // Try each element as the target value
    for (let i = 0; i < n; i++) {
        let currentCost = 0;

        // Calculate cost of making all 
        // elements equal to arr[i]
        for (let j = 0; j < n; j++) {
            currentCost += Math.abs(arr[j] - arr[i]);
        }

        // Update minimum cost if current cost is lower
        ans = Math.min(ans, currentCost);
    }

    return ans;
}

let arr = [1, 100, 101];
console.log(minCost(arr));

Output
100

[Expected Approach – 1] Using Binary Search – O(n Log (Range)) time and O(1) space

The idea is to utilize binary search to efficiently find the optimal value to which all array elements should be converted. Since the total cost function forms a convex curve (first decreasing, then increasing) across the range of possible values, we can use binary search to locate the minimum point of this curve by comparing the cost at a mid-point with the cost at mid-point minus one, which tells us which direction to search further.

Step by step approach:

  1. Find the minimum and maximum values in the array to establish the search range
  2. Use binary search between the minimum and maximum values to locate the optimal target value
  3. For each trial value, calculate the total cost of converting all array elements to that value
  4. Compare the cost at current mid-point with cost at mid-point minus one to determine search direction
  5. Continue narrowing the search range until finding the minimum cost configuration
C++
// C++ program to Make all array 
// elements equal with minimum cost
#include <bits/stdc++.h>
using namespace std;

// Function to find the cost of changing
// array values to mid.
int findCost(vector<int> &arr, int mid) {
    int n = arr.size();
    int ans = 0;
    for (int i=0; i<n; i++) {
        ans += abs(arr[i] - mid);
    }
    return ans;
}

// Function which finds the minimum cost 
// to make array elements equal.
int minCost(vector<int> &arr) {
    int n = arr.size();

    int mini = INT_MAX, maxi = INT_MIN;
    
    // Find the minimum and maximum value.
    for (int i=0; i<n; i++) {
        mini = min(mini, arr[i]);
        maxi = max(maxi, arr[i]);
    }
    
    int s = mini, e = maxi;
    int ans = INT_MAX;
    
    while (s <= e) {
        int mid = s + (e-s)/2;
        
        int cost1 = findCost(arr, mid);
        int cost2 = findCost(arr, mid-1);
        
        if (cost1 < cost2) {
            ans = cost1;
            s = mid + 1;
        }
        else {
            e = mid - 1;
        }
    }
    
    return ans;
}

int main() {
    vector<int> arr = {1, 100, 101};
    cout << minCost(arr);
    
    return 0;
}
Java
// Java program to Make all array 
// elements equal with minimum cost
import java.util.*;

class GfG {

    // Function to find the cost of changing
    // array values to mid.
    static int findCost(int[] arr, int mid) {
        int n = arr.length;
        int ans = 0;
        for (int i = 0; i < n; i++) {
            ans += Math.abs(arr[i] - mid);
        }
        return ans;
    }

    // Function which finds the minimum cost 
    // to make array elements equal.
    static int minCost(int[] arr) {
        int n = arr.length;

        int mini = Integer.MAX_VALUE, maxi = Integer.MIN_VALUE;

        // Find the minimum and maximum value.
        for (int i = 0; i < n; i++) {
            mini = Math.min(mini, arr[i]);
            maxi = Math.max(maxi, arr[i]);
        }

        int s = mini, e = maxi;
        int ans = Integer.MAX_VALUE;

        while (s <= e) {
            int mid = s + (e - s) / 2;

            int cost1 = findCost(arr, mid);
            int cost2 = findCost(arr, mid - 1);

            if (cost1 < cost2) {
                ans = cost1;
                s = mid + 1;
            } else {
                e = mid - 1;
            }
        }

        return ans;
    }

    public static void main(String[] args) {
        int[] arr = {1, 100, 101};
        System.out.println(minCost(arr));
    }
}
Python
# Python program to Make all array 
# elements equal with minimum cost

# Function to find the cost of changing
# array values to mid.
def findCost(arr, mid):
    n = len(arr)
    ans = 0
    for i in range(n):
        ans += abs(arr[i] - mid)
    return ans

# Function which finds the minimum cost 
# to make array elements equal.
def minCost(arr):
    n = len(arr)

    mini = float('inf')
    maxi = float('-inf')

    # Find the minimum and maximum value.
    for i in range(n):
        mini = min(mini, arr[i])
        maxi = max(maxi, arr[i])

    s = mini
    e = maxi
    ans = float('inf')

    while s <= e:
        mid = s + (e - s) // 2

        cost1 = findCost(arr, mid)
        cost2 = findCost(arr, mid - 1)

        if cost1 < cost2:
            ans = cost1
            s = mid + 1
        else:
            e = mid - 1

    return ans

if __name__ == "__main__":
    arr = [1, 100, 101]
    print(minCost(arr))
C#
// C# program to Make all array 
// elements equal with minimum cost
using System;

class GfG {

    // Function to find the cost of changing
    // array values to mid.
    static int findCost(int[] arr, int mid) {
        int n = arr.Length;
        int ans = 0;
        for (int i = 0; i < n; i++) {
            ans += Math.Abs(arr[i] - mid);
        }
        return ans;
    }

    // Function which finds the minimum cost 
    // to make array elements equal.
    static int minCost(int[] arr) {
        int n = arr.Length;

        int mini = int.MaxValue, maxi = int.MinValue;

        // Find the minimum and maximum value.
        for (int i = 0; i < n; i++) {
            mini = Math.Min(mini, arr[i]);
            maxi = Math.Max(maxi, arr[i]);
        }

        int s = mini, e = maxi;
        int ans = int.MaxValue;

        while (s <= e) {
            int mid = s + (e - s) / 2;

            int cost1 = findCost(arr, mid);
            int cost2 = findCost(arr, mid - 1);

            if (cost1 < cost2) {
                ans = cost1;
                s = mid + 1;
            } else {
                e = mid - 1;
            }
        }

        return ans;
    }

    static void Main() {
        int[] arr = {1, 100, 101};
        Console.WriteLine(minCost(arr));
    }
}
JavaScript
// JavaScript program to Make all array 
// elements equal with minimum cost

// Function to find the cost of changing
// array values to mid.
function findCost(arr, mid) {
    let n = arr.length;
    let ans = 0;
    for (let i = 0; i < n; i++) {
        ans += Math.abs(arr[i] - mid);
    }
    return ans;
}

// Function which finds the minimum cost 
// to make array elements equal.
function minCost(arr) {
    let n = arr.length;

    let mini = Number.MAX_SAFE_INTEGER, maxi = Number.MIN_SAFE_INTEGER;

    // Find the minimum and maximum value.
    for (let i = 0; i < n; i++) {
        mini = Math.min(mini, arr[i]);
        maxi = Math.max(maxi, arr[i]);
    }

    let s = mini, e = maxi;
    let ans = Number.MAX_SAFE_INTEGER;

    while (s <= e) {
        let mid = Math.floor(s + (e - s) / 2);

        let cost1 = findCost(arr, mid);
        let cost2 = findCost(arr, mid - 1);

        if (cost1 < cost2) {
            ans = cost1;
            s = mid + 1;
        } else {
            e = mid - 1;
        }
    }

    return ans;
}

let arr = [1, 100, 101];
console.log(minCost(arr));

Output
100

[Expected Approach – 2] Using Sorting – O(n Log n) time and O(1) space

The idea is to find the optimal value to which all elements should be equalized, which must be one of the existing array elements. By sorting the array first and then iterating through each element as a potential target value, we calculate the cost of transforming all other elements to that value by efficiently tracking the sum of elements to the left and right of the current position.

Step by step approach:

  1. Sort the array to process elements in ascending order.
  2. For each element as a potential target value, calculate two costs: bringing smaller elements up and larger elements down.
  3. Track left and right sums to compute these costs efficiently in constant time per iteration.
    • Bringing smaller elements up costs: (current value × number of smaller elements) – (sum of smaller elements)
    • Bringing larger elements down costs: (sum of larger elements) – (current value × number of larger elements)
  4. Compare the current cost with minimum cost.
C++
// C++ program to Make all array 
// elements equal with minimum cost
#include <bits/stdc++.h>
using namespace std;

// Function which finds the minimum cost 
// to make array elements equal.
int minCost(vector<int> &arr) {
    int n = arr.size();

    // Sort the array
    sort(arr.begin(), arr.end());
    
    // Variable to store sum of elements
    // to the right side.
    int right = 0;
    for (int i=0; i<n; i++) {
        right += arr[i];
    }
    
    int ans = INT_MAX;
    int left = 0;
    
    for (int i=0; i<n; i++) {
        
        // Remove the current element from right sum.
        right -= arr[i];
        
        // Find cost of incrementing left side elements
        int leftCost = i * arr[i] - left;
        
        // Find cost of decrementing right side elements.
        int rightCost = right - (n-1-i) * arr[i];
        
        ans = min(ans, leftCost + rightCost);
        
        // Add current value to left sum 
        left += arr[i];
    }
    
    return ans;
}

int main() {
    vector<int> arr = {1, 100, 101};
    cout << minCost(arr);
    
    return 0;
}
Java
// Java program to Make all array 
// elements equal with minimum cost
import java.util.*;

class GfG {

    // Function which finds the minimum cost 
    // to make array elements equal.
    static int minCost(int[] arr) {
        int n = arr.length;

        // Sort the array
        Arrays.sort(arr);
        
        // Variable to store sum of elements
        // to the right side.
        int right = 0;
        for (int i = 0; i < n; i++) {
            right += arr[i];
        }

        int ans = Integer.MAX_VALUE;
        int left = 0;

        for (int i = 0; i < n; i++) {

            // Remove the current element from right sum.
            right -= arr[i];

            // Find cost of incrementing left side elements
            int leftCost = i * arr[i] - left;

            // Find cost of decrementing right side elements.
            int rightCost = right - (n - 1 - i) * arr[i];

            ans = Math.min(ans, leftCost + rightCost);

            // Add current value to left sum 
            left += arr[i];
        }

        return ans;
    }

    public static void main(String[] args) {
        int[] arr = {1, 100, 101};
        System.out.println(minCost(arr));
    }
}
Python
# Python program to Make all array 
# elements equal with minimum cost

# Function which finds the minimum cost 
# to make array elements equal.
def minCost(arr):
    n = len(arr)

    # Sort the array
    arr.sort()

    # Variable to store sum of elements
    # to the right side.
    right = sum(arr)

    ans = float('inf')
    left = 0

    for i in range(n):

        # Remove the current element from right sum.
        right -= arr[i]

        # Find cost of incrementing left side elements
        leftCost = i * arr[i] - left

        # Find cost of decrementing right side elements.
        rightCost = right - (n - 1 - i) * arr[i]

        ans = min(ans, leftCost + rightCost)

        # Add current value to left sum 
        left += arr[i]

    return ans

if __name__ == "__main__":
    arr = [1, 100, 101]
    print(minCost(arr))
C#
// C# program to Make all array 
// elements equal with minimum cost
using System;

class GfG {

    // Function which finds the minimum cost 
    // to make array elements equal.
    static int minCost(int[] arr) {
        int n = arr.Length;

        // Sort the array
        Array.Sort(arr);

        // Variable to store sum of elements
        // to the right side.
        int right = 0;
        for (int i = 0; i < n; i++) {
            right += arr[i];
        }

        int ans = int.MaxValue;
        int left = 0;

        for (int i = 0; i < n; i++) {

            // Remove the current element from right sum.
            right -= arr[i];

            // Find cost of incrementing left side elements
            int leftCost = i * arr[i] - left;

            // Find cost of decrementing right side elements.
            int rightCost = right - (n - 1 - i) * arr[i];

            ans = Math.Min(ans, leftCost + rightCost);

            // Add current value to left sum 
            left += arr[i];
        }

        return ans;
    }

    static void Main() {
        int[] arr = {1, 100, 101};
        Console.WriteLine(minCost(arr));
    }
}
JavaScript
// JavaScript program to Make all array 
// elements equal with minimum cost

// Function which finds the minimum cost 
// to make array elements equal.
function minCost(arr) {
    let n = arr.length;

    // Sort the array
    arr.sort((a, b) => a - b);

    // Variable to store sum of elements
    // to the right side.
    let right = 0;
    for (let i = 0; i < n; i++) {
        right += arr[i];
    }

    let ans = Number.MAX_SAFE_INTEGER;
    let left = 0;

    for (let i = 0; i < n; i++) {

        // Remove the current element from right sum.
        right -= arr[i];

        // Find cost of incrementing left side elements
        let leftCost = i * arr[i] - left;

        // Find cost of decrementing right side elements.
        let rightCost = right - (n - 1 - i) * arr[i];

        ans = Math.min(ans, leftCost + rightCost);

        // Add current value to left sum 
        left += arr[i];
    }

    return ans;
}

let arr = [1, 100, 101];
console.log(minCost(arr));

Output
100


Next Article
Article Tags :
Practice Tags :

Similar Reads