Equalizing an Array with the Least Possible Cost

Last Updated : 16 Dec, 2025

Given an array, arr[], and the cost array cost[], Find the minimum cost to make all the array elements equal by incrementing or decrementing the element at any index by 1. The cost of the increment or decrement operation for the element at index i is the cost[i].

Examples:

Input: arr[] = [1, 3, 5, 2], cost[] = [2, 3, 1, 14]
Output: 8
Explanation: On making all elements equal to 2 the cost is 1*2 + 1*3 + 3*1 = 8 which is the minimum cost.

Input: arr[] = [3, 3, 3, 3, 3], cost[] = [1, 2, 3, 4, 5]
Output: 0
Explanation: All are same already in the array arr[].

[Naive Approach] Try every possible target - O(n × (max_len - min_len)) Time and O(1) Space

The idea is to try every possible final stick length between the minimum and maximum values and calculate the cost to convert all sticks to that length. The minimum cost among all these possibilities is the answer.

C++
#include <iostream>
#include <vector>
#include <climits>
#include <cstdlib>
using namespace std;

// Compute total cost if all sticks become target
long long getCost(int target, vector<int> &length, vector<int> &cost) {

    long long total = 0;

    // Compute cost for each stick
    for (int i = 0; i < length.size(); i++) {
        total += 1LL * abs(length[i] - target) * cost[i];
    }

    return total;
}

long long minimumCost(int n, vector<int> &length, vector<int> &cost) {

    // Find minimum and maximum stick length
    int Lmin = length[0];
    int Lmax = length[0];

    for (int i = 1; i < n; i++) {
        Lmin = min(Lmin, length[i]);
        Lmax = max(Lmax, length[i]);
    }

    long long ans = LLONG_MAX;

    // Try all possible target lengths
    for (int target = Lmin; target <= Lmax; target++) {
        ans = min(ans, getCost(target, length, cost));
    }

    return ans;
}

int main() {

    vector<int> length = {1, 3, 5, 2};
    vector<int> cost = {2, 3, 1, 14};

    cout << minimumCost(length.size(), length, cost) << endl;

    return 0;
}
Java
import java.util.ArrayList;

class GFG {

    // Compute total cost if all sticks become target
    static long getCost(int target, int[] length, int[] cost) {

        long total = 0;

        // Compute cost for each stick
        for (int i = 0; i < length.length; i++) {
            total += (long)Math.abs(length[i] - target) * cost[i];
        }

        return total;
    }

    static long minimumCost(int n, int[] length, int[] cost) {

        // Find minimum and maximum stick length
        int Lmin = length[0];
        int Lmax = length[0];

        for (int i = 1; i < n; i++) {
            Lmin = Math.min(Lmin, length[i]);
            Lmax = Math.max(Lmax, length[i]);
        }

        long ans = Long.MAX_VALUE;

        // Try all possible target lengths
        for (int target = Lmin; target <= Lmax; target++) {
            ans = Math.min(ans, getCost(target, length, cost));
        }

        return ans;
    }

    public static void main(String[] args) {

        int[] length = {1, 3, 5, 2};
        int[] cost = {2, 3, 1, 14};

        System.out.println(minimumCost(length.length, length, cost));
    }
}
Python
# Compute total cost if all sticks become target
def getCost(target, length, cost):

    total = 0

    # Compute cost for each stick
    for i in range(len(length)):
        total += abs(length[i] - target) * cost[i]

    return total


def minimumCost(n, length, cost):

    # Find minimum and maximum stick length
    Lmin = length[0]
    Lmax = length[0]

    for i in range(1, n):
        Lmin = min(Lmin, length[i])
        Lmax = max(Lmax, length[i])

    ans = 10**18

    # Try all possible target lengths
    for target in range(Lmin, Lmax + 1):
        ans = min(ans, getCost(target, length, cost))

    return ans


if __name__ == "__main__":

    length = [1, 3, 5, 2]
    cost = [2, 3, 1, 14]

    print(minimumCost(len(length), length, cost))
C#
using System;

class GFG {

    // Compute total cost if all sticks become target
    static long getCost(int target, int[] length, int[] cost) {

        long total = 0;

        // Compute cost for each stick
        for (int i = 0; i < length.Length; i++) {
            total += Math.Abs(length[i] - target) * cost[i];
        }

        return total;
    }

    static long minimumCost(int n, int[] length, int[] cost) {

        // Find minimum and maximum stick length
        int Lmin = length[0];
        int Lmax = length[0];

        for (int i = 1; i < n; i++) {
            Lmin = Math.Min(Lmin, length[i]);
            Lmax = Math.Max(Lmax, length[i]);
        }

        long ans = long.MaxValue;

        // Try all possible target lengths
        for (int target = Lmin; target <= Lmax; target++) {
            ans = Math.Min(ans, getCost(target, length, cost));
        }

        return ans;
    }

    static void Main() {

        int[] length = {1, 3, 5, 2};
        int[] cost = {2, 3, 1, 14};

        Console.WriteLine(minimumCost(length.Length, length, cost));
    }
}
JavaScript
// Compute total cost if all sticks become target
function getCost(target, length, cost) {

    let total = 0;

    // Compute cost for each stick
    for (let i = 0; i < length.length; i++) {
        total += Math.abs(length[i] - target) * cost[i];
    }

    return total;
}

function minimumCost(n, length, cost) {

    // Find minimum and maximum stick length
    let Lmin = length[0];
    let Lmax = length[0];

    for (let i = 1; i < n; i++) {
        Lmin = Math.min(Lmin, length[i]);
        Lmax = Math.max(Lmax, length[i]);
    }

    let ans = Number.MAX_SAFE_INTEGER;

    // Try all possible target lengths
    for (let target = Lmin; target <= Lmax; target++) {
        ans = Math.min(ans, getCost(target, length, cost));
    }

    return ans;
}

// Driver Code
let length = [1, 3, 5, 2];
let cost = [2, 3, 1, 14];

console.log(minimumCost(length.length, length, cost));

Output
8

[Expected Approach 1] Using Prefix and Suffix Weighted Costs - O(n log n) Time and O(n) Space

We try using each stick’s current length as the target length. For every target T equal to one of the stick lengths, we calculate the total cost by summing the prefix cost to increase sticks on the left and the suffix cost to decrease sticks on the right. The minimum total cost among all these target lengths is the answer.

C++
#include <iostream>
#include <vector>
#include <algorithm>
#include <array>
#include <climits>
using namespace std;

long long minimumCost(int n, vector<int> &length, vector<int> &cost) {

    long long ans = LLONG_MAX;

    // Pair each stick length with its cost
    vector<array<long long, 2>> v;
    for (int i = 0; i < n; i++) {
        v.push_back({length[i], cost[i]});
    }

    // Sort sticks by length
    sort(v.begin(), v.end());

    // Prefix and suffix cost arrays
    vector<long long> a(n, 0);
    vector<long long> b(n, 0);

    // Compute prefix costs
    long long cur = 0;
    long long sum = v[0][1];
    for (int i = 1; i < n; i++) {
        cur += (v[i][0] - v[i - 1][0]) * sum;
        a[i] = cur;
        sum += v[i][1];
    }

    // Compute suffix costs
    cur = 0;
    sum = v[n - 1][1];
    for (int i = n - 2; i >= 0; i--) {
        cur += (v[i + 1][0] - v[i][0]) * sum;
        b[i] = cur;
        sum += v[i][1];
    }

    // Find minimum total cost
    for (int i = 0; i < n; i++) {
        ans = min(ans, a[i] + b[i]);
    }

    return ans;
}

int main() {

    vector<int> length = {1, 3, 5, 2};
    vector<int> cost = {2, 3, 1, 14};

    cout << minimumCost(length.size(), length, cost) << endl;

    return 0;
}
Java
import java.util.Arrays;

class GFG {

    static long minimumCost(int n, int[] length, int[] cost) {

        long ans = Long.MAX_VALUE;

        long[][] v = new long[n][2];

        // Pair each stick length with its cost
        for (int i = 0; i < n; i++) {
            v[i][0] = length[i];
            v[i][1] = cost[i];
        }

        // Sort sticks by length
        Arrays.sort(v, (a, b) -> Long.compare(a[0], b[0]));

        long[] a = new long[n];
        long[] b = new long[n];

        // Compute prefix costs
        long cur = 0;
        long sum = v[0][1];
        for (int i = 1; i < n; i++) {
            cur += (v[i][0] - v[i - 1][0]) * sum;
            a[i] = cur;
            sum += v[i][1];
        }

        // Compute suffix costs
        cur = 0;
        sum = v[n - 1][1];
        for (int i = n - 2; i >= 0; i--) {
            cur += (v[i + 1][0] - v[i][0]) * sum;
            b[i] = cur;
            sum += v[i][1];
        }

        // Find minimum total cost
        for (int i = 0; i < n; i++) {
            ans = Math.min(ans, a[i] + b[i]);
        }

        return ans;
    }

    public static void main(String[] args) {

        int[] length = {1, 3, 5, 2};
        int[] cost = {2, 3, 1, 14};

        System.out.println(minimumCost(length.length, length, cost));
    }
}
Python
def minimumCost(n, length, cost):

    # Pair each stick length with its cost
    v = list(zip(length, cost))

    # Sort sticks by length
    v.sort()

    a = [0] * n
    b = [0] * n

    # Compute prefix costs
    cur = 0
    total = v[0][1]
    for i in range(1, n):
        cur += (v[i][0] - v[i - 1][0]) * total
        a[i] = cur
        total += v[i][1]

    # Compute suffix costs
    cur = 0
    total = v[n - 1][1]
    for i in range(n - 2, -1, -1):
        cur += (v[i + 1][0] - v[i][0]) * total
        b[i] = cur
        total += v[i][1]

    # Find minimum total cost
    ans = 10**18
    for i in range(n):
        ans = min(ans, a[i] + b[i])

    return ans


if __name__ == "__main__":

    length = [1, 3, 5, 2]
    cost = [2, 3, 1, 14]

    print(minimumCost(len(length), length, cost))
C#
using System;

class GFG {

    static long minimumCost(int n, int[] length, int[] cost) {

        long ans = long.MaxValue;

        long[,] v = new long[n, 2];

        // Pair each stick length with its cost
        for (int i = 0; i < n; i++) {
            v[i, 0] = length[i];
            v[i, 1] = cost[i];
        }

        // Sort sticks by length
        Array.Sort(length, cost);

        long[] a = new long[n];
        long[] b = new long[n];

        // Compute prefix costs
        long cur = 0;
        long sum = cost[0];
        for (int i = 1; i < n; i++) {
            cur += (length[i] - length[i - 1]) * sum;
            a[i] = cur;
            sum += cost[i];
        }

        // Compute suffix costs
        cur = 0;
        sum = cost[n - 1];
        for (int i = n - 2; i >= 0; i--) {
            cur += (length[i + 1] - length[i]) * sum;
            b[i] = cur;
            sum += cost[i];
        }

        // Find minimum total cost
        for (int i = 0; i < n; i++) {
            ans = Math.Min(ans, a[i] + b[i]);
        }

        return ans;
    }

    static void Main() {

        int[] length = {1, 3, 5, 2};
        int[] cost = {2, 3, 1, 14};

        Console.WriteLine(minimumCost(length.Length, length, cost));
    }
}
JavaScript
function minimumCost(n, length, cost) {

    // Pair each stick length with its cost
    let v = [];
    for (let i = 0; i < n; i++) {
        v.push([length[i], cost[i]]);
    }

    // Sort sticks by length
    v.sort((a, b) => a[0] - b[0]);

    let a = new Array(n).fill(0);
    let b = new Array(n).fill(0);

    // Compute prefix costs
    let cur = 0;
    let sum = v[0][1];
    for (let i = 1; i < n; i++) {
        cur += (v[i][0] - v[i - 1][0]) * sum;
        a[i] = cur;
        sum += v[i][1];
    }

    // Compute suffix costs
    cur = 0;
    sum = v[n - 1][1];
    for (let i = n - 2; i >= 0; i--) {
        cur += (v[i + 1][0] - v[i][0]) * sum;
        b[i] = cur;
        sum += v[i][1];
    }

    // Find minimum total cost
    let ans = Number.MAX_SAFE_INTEGER;
    for (let i = 0; i < n; i++) {
        ans = Math.min(ans, a[i] + b[i]);
    }

    return ans;
}

// Driver Code
let length = [1, 3, 5, 2];
let cost = [2, 3, 1, 14];

console.log(minimumCost(length.length, length, cost));

Output
8

[Expected Approach 2] Using Weighted Median - O(n log n) Time and O(n) Space

To minimize the total adjustment cost, each stick’s increase or decrease cost contributes a weighted distance from the chosen target length. The total cost function becomes a convex function because it sums weighted absolute differences. The minimum of such a function always occurs at the weighted median of the stick lengths. Therefore, instead of testing all possible target lengths, we compute the weighted median and evaluate the cost at that point. This reduces the problem to sorting and a single pass computation, which is far more efficient than the naive method.

C++
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>

using namespace std;

// compute total cost for chosen target
long long getCost(int target, vector<int> &arr, vector<int> &cost) {
    long long total = 0;
    for (int i = 0; i < arr.size(); i++) {
        total += 1LL * abs(arr[i] - target) * cost[i];
    }
    return total;
}

// find weighted median as optimal target 
long long minimumCost(int n, vector<int> &arr, vector<int> &cost) {
    vector<pair<int,int>> v;
    for (int i = 0; i < n; i++) {
        v.push_back({arr[i], cost[i]});
    }

    sort(v.begin(), v.end());

    long long W = 0;
    for (auto &p : v) {
        W += p.second;
    }

    long long pref = 0;
    int target = v[0].first;

    for (int i = 0; i < n; i++) {
        pref += v[i].second;
        if (pref * 2 >= W) {
            target = v[i].first;
            break;
        }
    }

    // calculate final minimum cost
    return getCost(target, arr, cost);
}

int main() {
    vector<int> arr = {1, 3, 5, 2};
    vector<int> cost = {2, 3, 1, 14};

    cout << minimumCost(arr.size(), arr, cost);
    return 0;
}
Java
import java.util.Arrays;
import java.util.Comparator;

class GFG {

    // compute total cost for chosen target
    static long getCost(int target, int[] arr, int[] cost) {
        long total = 0;
        for (int i = 0; i < arr.length; i++) {
            total += 1L * Math.abs(arr[i] - target) * cost[i];
        }
        return total;
    }

    // find weighted median as optimal target
    static long minimumCost(int n, int[] arr, int[] cost) {
        int[][] v = new int[n][2];
        for (int i = 0; i < n; i++) {
            v[i][0] = arr[i];
            v[i][1] = cost[i];
        }

        Arrays.sort(v, Comparator.comparingInt(a -> a[0]));

        long W = 0;
        for (int i = 0; i < n; i++) {
            W += v[i][1];
        }

        long pref = 0;
        int target = v[0][0];

        for (int i = 0; i < n; i++) {
            pref += v[i][1];
            if (pref * 2 >= W) {
                target = v[i][0];
                break;
            }
        }

        // calculate final minimum cost
        return getCost(target, arr, cost);
    }

    public static void main(String[] args) {
        int[] arr = {1, 3, 5, 2};
        int[] cost = {2, 3, 1, 14};

        System.out.println(minimumCost(arr.length, arr, cost));
    }
}
Python
# compute total cost for chosen target
def getCost(target, arr, cost):
    total = 0
    for i in range(len(arr)):
        total += abs(arr[i] - target) * cost[i]
    return total

# find weighted median as optimal target
def minimumCost(n, arr, cost):
    v = list(zip(arr, cost))
    v.sort()

    W = sum(c for _, c in v)

    pref = 0
    target = v[0][0]

    for a, c in v:
        pref += c
        if pref * 2 >= W:
            target = a
            break

    # calculate final minimum cost
    return getCost(target, arr, cost)

if __name__ == "__main__":
    arr = [1, 3, 5, 2]
    cost = [2, 3, 1, 14]

    print(minimumCost(len(arr), arr, cost))
C#
using System;

class GFG {

    // compute total cost for chosen target 
    static long getCost(int target, int[] arr, int[] cost) {
        long total = 0;
        for (int i = 0; i < arr.Length; i++) {
            total += Math.Abs(arr[i] - target) * cost[i];
        }
        return total;
    }

    // find weighted median as optimal target 
    static long minimumCost(int n, int[] arr, int[] cost) {
        Array.Sort(arr, cost);

        long W = 0;
        for (int i = 0; i < n; i++) {
            W += cost[i];
        }

        long pref = 0;
        int target = arr[0];

        for (int i = 0; i < n; i++) {
            pref += cost[i];
            if (pref * 2 >= W) {
                target = arr[i];
                break;
            }
        }

        // calculate final minimum cost
        return getCost(target, arr, cost);
    }

    static void Main() {
        int[] arr = {1, 3, 5, 2};
        int[] cost = {2, 3, 1, 14};

        Console.WriteLine(minimumCost(arr.Length, arr, cost));
    }
}
JavaScript
// compute total cost for chosen target 
function getCost(target, arr, cost) {
    let total = 0;
    for (let i = 0; i < arr.length; i++) {
        total += Math.abs(arr[i] - target) * cost[i];
    }
    return total;
}

// find weighted median as optimal target 
function minimumCost(n, arr, cost) {
    let v = [];
    for (let i = 0; i < n; i++) {
        v.push([arr[i], cost[i]]);
    }

    v.sort((a, b) => a[0] - b[0]);

    let W = 0;
    for (let i = 0; i < n; i++) {
        W += v[i][1];
    }

    let pref = 0;
    let target = v[0][0];

    for (let i = 0; i < n; i++) {
        pref += v[i][1];
        if (pref * 2 >= W) {
            target = v[i][0];
            break;
        }
    }

    // calculate final minimum cost 
    return getCost(target, arr, cost);
}

// Driver Code
let arr = [1, 3, 5, 2];
let cost = [2, 3, 1, 14];

console.log(minimumCost(arr.length, arr, cost));

Output
8


Comment