#2448

Minimum Cost to Make Array Equal

candidate master · 1510 · lc hard +32 · verified · 46.7% accepted · 2,519 likes · top 31%

Description

You are given two 0-indexed integer arrays nums and cost of the same length n. You may increase or decrease any element of nums by 1; doing so on element i costs cost[i] per unit change.

Return the minimum total cost to make all elements of nums equal.

Example 1:

Input: nums = [1,3,5,2], cost = [2,3,1,14]
Output: 8
Explanation: We can make all the elements equal to 2 in the following way:
- Increase the 0th element one time. The cost is 2.
- Decrease the 1st element one time. The cost is 3.
- Decrease the 2nd element three times. The cost is 1 + 1 + 1 = 3.
The total cost is 2 + 3 + 3 = 8.
It can be shown that we cannot make the array equal with a smaller cost.

Example 2:

Input: nums = [2,2,2,2,2], cost = [4,2,8,1,3]
Output: 0
Explanation: All the elements are already equal, so no operations are needed.

Code

1
2
3