![]() |
VOOZH | about |
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[].
Table of Content
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.
8
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.
8
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.
8