Problem
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
fromnums
and increasenums[i]
by1
for a cost ofcost1
. - Choose two different indices
i
,j
, fromnums
and increasenums[i]
andnums[j]
by1
for a cost ofcost2
.
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
.
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^6
1 <= cost1 <= 10^6
1 <= cost2 <= 10^6
Solution
Method 1 – Greedy Enumeration
Intuition
To make all elements equal, we can choose a target value and calculate the cost to increase all elements to that value. For each element, we can use either single or double increment operations. Using as many double operations as possible is optimal if cost2 < 2 * cost1
.
Approach
- Find the maximum value in
nums
(let’s call itmx
). - For each possible target value from
mx
tomx + max(nums)
:- For each element, calculate the difference to the target.
- Use as many double operations as possible (pairs of increments), and single operations for the remainder.
- Compute the total cost for this target.
- Track the minimum cost.
- Return the minimum cost modulo
10^9 + 7
.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n * R)
where n is the length of nums and R is the range of possible target values. - 🧺 Space complexity:
O(1)
.