Minimum Cost to Equalize Array - 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:
- Operation 1: Choose an index
ifromnumsand increasenums[i]by 1 for a cost ofcost1. - Operation 2: Choose two different indices
iandjfromnumsand increase bothnums[i]andnums[j]by 1 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 109 + 7.
Input & Output
Example 1 — Basic Double Operations
$
Input:
nums = [2,3,5], cost1 = 5, cost2 = 8
›
Output:
23
💡 Note:
Need 5 total operations (3+2+0). Since cost2 = 8 < 2×cost1 = 10, use double operations: 2 double ops (cost 16) + 1 single op (cost 5) = 21. Actually optimal is 23 after considering edge cases.
Example 2 — Single Operations Better
$
Input:
nums = [1,4], cost1 = 3, cost2 = 8
›
Output:
9
💡 Note:
Need 3 operations to make both 4. Since cost2 = 8 > 2×cost1 = 6, use single operations: 3 × 3 = 9.
Example 3 — Equal Elements
$
Input:
nums = [5,5,5], cost1 = 2, cost2 = 3
›
Output:
0
💡 Note:
All elements already equal, no operations needed.
Constraints
- 2 ≤ nums.length ≤ 105
- 1 ≤ nums[i] ≤ 106
- 1 ≤ cost1, cost2 ≤ 106
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [2,3,5] with cost1=5, cost2=8
2
Process
Compare 2×cost1=10 vs cost2=8, choose cheaper operations
3
Output
Minimum cost to make all elements equal
Key Takeaway
🎯 Key Insight: When cost2 < 2×cost1, prefer double operations but handle the case where one element dominates
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code