VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-cost-to-make-array-equal-by-increment-decrementing-elements/

⇱ Equalizing an Array with the Least Possible Cost - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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.


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.


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.


Output
8


Comment