#2448

Minimum Cost to Make Array Equal

Hard
ArrayBinary SearchGreedySortingPrefix SumBinary SearchGreedy AlgorithmsConvex Functions
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log m)
Space
O(1)
O(1)
💡

Intuition

Time O(n log m)Space O(1)

The optimal solution leverages binary search to find the best target value that minimizes the total cost. By calculating the cost for a range of potential targets, we can efficiently hone in on the minimum cost.

⚙️

Algorithm

4 steps
  1. 1Step 1: Define a function to calculate the total cost for a given target.
  2. 2Step 2: Use binary search to find the optimal target value between the minimum and maximum values of nums.
  3. 3Step 3: For each midpoint in the binary search, calculate the cost and adjust the search range based on whether the cost increases or decreases.
  4. 4Step 4: Return the minimum cost found.
solution.py13 lines
1def minCost(nums, cost):
2    def calculate_cost(target):
3        return sum(abs(num - target) * c for num, c in zip(nums, cost))
4    left, right = min(nums), max(nums)
5    while left < right:
6        mid = (left + right) // 2
7        cost_mid = calculate_cost(mid)
8        cost_mid_plus_one = calculate_cost(mid + 1)
9        if cost_mid < cost_mid_plus_one:
10            right = mid
11        else:
12            left = mid + 1
13    return calculate_cost(left)

Complexity note: The time complexity is O(n log m) where n is the number of elements in nums and m is the range of values in nums, due to the binary search over possible target values and the cost calculation for each target.

  • 1Changing elements to a target value that already exists in nums is optimal.
  • 2The cost function is convex, allowing for efficient search methods like binary search.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.