Minimum Cost to Equalize Array

You are given an integer array nums and two integers cost1 and cost2. You are allowed to perform either of the following operations any number of times:

  • Choose an index i from nums and increase nums[i] by 1 for a cost of cost1.
  • Choose two different indices i, j, from nums and increase nums[i] and nums[j] by 1 for a cost of cost2.

Return the minimum cost required to make all elements in the array equal.

Since the answer may be very large, return it modulo 10^9 + 7.

Example 1
Inputnums = [4,1], cost1 = 5, cost2 = 2
Output15
Increasing nums[1] three times makes the array [4, 4] with a total cost of 15.
Example 2
Inputnums = [2,3,3,3,5], cost1 = 2, cost2 = 1
Output6
Using four two-index operations and one single-index operation makes all elements equal to 5 with a total cost of 6.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^6
  • 1 <= cost1 <= 10^6
  • 1 <= cost2 <= 10^6

Asked at 2 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