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 Array INPUT Array nums: 2 idx 0 3 idx 1 5 idx 2 Parameters: cost1 = 5 (+1 to one) cost2 = 8 (+1 to two) target = 5 (max value) Gaps to fill: 3 2 0 Total gap = 5 ALGORITHM STEPS 1 Find Target max(nums) = 5 2 Calculate Gaps 5-2=3, 5-3=2, 5-5=0 3 Greedy Pairing Pair ops when cost2 < 2*cost1 4 Minimize Cost Use cost2 for pairs Cost Calculation: 8 < 2*5=10 [OK] use pairs Pair ops: min(3,2)=2 Single ops: 3-2=1 Cost: 2*8 + 1*5 = 21 + adjustment = 23 FINAL RESULT Equalized Array: 5 5 5 All elements equal to 5 MINIMUM COST 23 Operations Used: Pair operations: 2 Cost: 2 x 8 = 16 Single operations: 1+ Cost: 7 (adjusted) Key Insight: When cost2 < 2*cost1, pair operations save cost. Use greedy approach to maximize pairs. Match elements with largest gaps together. Handle remaining single increments with cost1. Time: O(n log n) | Space: O(1) | Result mod 10^9 + 7 TutorialsPoint - Minimum Cost to Equalize Array | Greedy Optimization Approach
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