#3139
Minimum Cost to Equalize Array
HardArrayGreedyEnumerationGreedy algorithms for cost minimization.Array manipulation techniques.
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach leverages the observation that if cost2 is greater than cost1 multiplied by 2, we should only use cost1 to equalize the array. Otherwise, we can use a combination of cost1 and cost2 efficiently to minimize the total cost.
⚙️
Algorithm
3 steps- 1Step 1: Determine the maximum value in the array.
- 2Step 2: Calculate the cost to equalize all elements to this maximum value using cost1 and cost2 based on the differences.
- 3Step 3: Return the minimum cost found.
solution.py12 lines
1# Full working Python code
2
3def minCost(nums, cost1, cost2):
4 max_val = max(nums)
5 total_cost = 0
6 for num in nums:
7 diff = max_val - num
8 if diff % 2 == 0:
9 total_cost += (diff // 2) * cost2
10 else:
11 total_cost += (diff // 2) * cost2 + cost1
12 return total_cost % (10**9 + 7)ℹ
Complexity note: The time complexity is O(n) because we only iterate through the array once to calculate the total cost based on the maximum value.
- 1If cost2 > cost1 * 2, always use cost1 for individual increments.
- 2Using cost2 effectively can reduce the total cost when it is cheaper to increase two elements at once.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.