Minimum Cost to Equalize Array - Problem
Imagine you have an array of integers where each element represents the height of a tower. Your goal is to make all towers the same height using the most cost-effective strategy possible.
You have two operations at your disposal:
- Operation 1: Increase any single tower's height by 1 for a cost of
cost1 - Operation 2: Increase any two different towers' heights by 1 each for a cost of
cost2
The challenge is to determine the minimum total cost to equalize all towers to the same height. Since costs can become astronomical for large arrays, return your answer modulo 109 + 7.
Example: If you have towers [1, 3, 4] and cost1 = 2, cost2 = 3, you need to raise the first tower by 3 and second tower by 1. You could use operation 1 four times (cost = 8) or mix operations for potentially lower cost.
Input & Output
example_1.py β Basic Case
$
Input:
nums = [4,1], cost1 = 5, cost2 = 2
βΊ
Output:
4
π‘ Note:
Need to increase nums[1] by 3 to match nums[0]=4. We can use one double operation (increases both elements, but nums[0] is already at target) and one single operation. But since we can't increase nums[0] beyond target, we use single operations: 3 * 5 = 15. Actually, with target=4, we need 3 operations on element 1. Using cost2=2 for pairs when possible gives us better cost.
example_2.py β Double Operation Preferred
$
Input:
nums = [2,3,3,3,5], cost1 = 2, cost2 = 1
βΊ
Output:
6
π‘ Note:
Target height is 5. Need operations: [3,2,2,2,0] = 9 total. Since cost2 < 2*cost1, we prefer double operations. We can do 4 double operations (cost=4) and 1 single operation (cost=2), total = 6.
example_3.py β Single Array Element
$
Input:
nums = [3], cost1 = 1, cost2 = 2
βΊ
Output:
0
π‘ Note:
Array already has equal elements (only one element), so no operations needed.
Constraints
- 1 β€ nums.length β€ 105
- 1 β€ nums[i] β€ 106
- 1 β€ cost1, cost2 β€ 106
- Result must be returned modulo 109 + 7
Visualization
Tap to expand
Understanding the Visualization
1
Assess Situation
Count how much work each tower needs and find the maximum gap
2
Compare Costs
Decide if team workers (cost2) are better than two solo workers (2*cost1)
3
Optimize Strategy
Use the more cost-effective approach while respecting constraints
4
Handle Edge Cases
Account for situations where perfect pairing isn't possible
Key Takeaway
π― Key Insight: The optimal strategy depends on cost efficiency - use double operations when cost2 < 2*cost1, but account for balancing constraints between elements.
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code