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 i from nums and increase nums[i] by 1 for a cost of cost1.
  • Operation 2: Choose two different indices i and j from nums and increase both 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 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
Minimum Cost to Equalize Array235Target: max = 5Operations needed: 3 + 2 + 0 = 5Single: cost1 = 5Double: cost2 = 8Compare: 2×5 = 10 vs 8Double operations cheaper!Optimal: 2 double + 1 single = 16 + 5 = 21But need to check edge cases for final answerOutput: 23
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
Asked in
Google 15 Microsoft 12 Amazon 8
12.5K Views
Medium Frequency
~35 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen