Skip to content

2448. Minimum Cost to Make Array Equal 👍

  • Time: $O(n\log (\max(\texttt{nums}) - \min(\texttt{nums})))$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
 public:
  long long minCost(vector<int>& nums, vector<int>& cost) {
    long ans = 0;
    int l = ranges::min(nums);
    int r = ranges::max(nums);

    while (l < r) {
      const int m = (l + r) / 2;
      const long cost1 = getCost(nums, cost, m);
      const long cost2 = getCost(nums, cost, m + 1);
      ans = min(cost1, cost2);
      if (cost1 < cost2)
        r = m;
      else
        l = m + 1;
    }

    return ans;
  }

 private:
  long getCost(const vector<int>& nums, const vector<int>& cost, int target) {
    long res = 0;
    for (int i = 0; i < nums.size(); ++i)
      res += static_cast<long>(abs(nums[i] - target)) * cost[i];
    return res;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
  public long minCost(int[] nums, int[] cost) {
    long ans = 0;
    int l = Arrays.stream(nums).min().getAsInt();
    int r = Arrays.stream(nums).max().getAsInt();

    while (l < r) {
      final int m = (l + r) / 2;
      final long cost1 = getCost(nums, cost, m);
      final long cost2 = getCost(nums, cost, m + 1);
      ans = Math.min(cost1, cost2);
      if (cost1 < cost2)
        r = m;
      else
        l = m + 1;
    }

    return ans;
  }

  private long getCost(int[] nums, int[] cost, int target) {
    long res = 0;
    for (int i = 0; i < nums.length; ++i)
      res += Math.abs(nums[i] - target) * (long) cost[i];
    return res;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
  def minCost(self, nums: List[int], cost: List[int]) -> int:
    ans = 0
    l = min(nums)
    r = max(nums)

    def getCost(target: int) -> int:
      return sum(abs(num - target) * c for num, c in zip(nums, cost))

    while l < r:
      m = (l + r) // 2
      cost1 = getCost(m)
      cost2 = getCost(m + 1)
      ans = min(cost1, cost2)
      if cost1 < cost2:
        r = m
      else:
        l = m + 1

    return ans