Minimum Cost to Make Array Equal

You are given two 0-indexed arrays nums and cost consisting each of n positive integers.

You can do the following operation any number of times:

  • Increase or decrease any element of the array nums by 1.

The cost of doing one operation on the i^th element is cost[i].

Return the minimum total cost such that all the elements of the array nums become equal.

Example 1
Inputnums = [1,3,5,2], cost = [2,3,1,14]
Output8
We can make all the elements equal to 2 with total cost 2 + 3 + 3 = 8, and no smaller cost is possible.
Example 2
Inputnums = [2,2,2,2,2], cost = [4,2,8,1,3]
Output0
All the elements are already equal, so no operations are needed.

Constraints

  • n == nums.length == cost.length
  • 1 <= n <= 10^5
  • 1 <= nums[i], cost[i] <= 10^6
  • Test cases are generated in a way that the output doesn't exceed 2^53-1

Asked at 6 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate