---
# System prepended metadata

title: 2602. Minimum Operations to Make All Array Elements Equal
tags: [Leetcode, Prefix Sum, Binary Search, Medium]

---

# 2602. Minimum Operations to Make All Array Elements Equal
###### tags: `Leetcode` `Medium` `Prefix Sum` `Binary Search`
Link: https://leetcode.com/problems/minimum-operations-to-make-all-array-elements-equal/description/
## 思路
对整个```nums``` array进行排序
接下来binary search找到第一个比query大的数字 nums[start]
那么想要把它前面的数字都变成query 需要```q*start-前面所有数字的和```
把它和它后面的数字都变成query 需要```整个array所有数字的和-前面数字的和-q*(len(nums)-start)```
## Code
```python=
class Solution:
    def minOperations(self, nums: List[int], queries: List[int]) -> List[int]:
        nums.sort()
        prefix = [0]*(len(nums)+1)
        for i, num in enumerate(nums):
            prefix[i+1] = prefix[i]+num
        ans = []
        for q in queries:
            start, mid, end = 0, 0, len(nums)
            while start<end:
                mid = start+(end-start)//2
                if nums[mid]<q: start = mid+1
                else: end = mid
            leftSum = q*start-prefix[start]
            rightSum = prefix[-1]-prefix[start]-q*(len(nums)-start)
            ans.append(leftSum+rightSum)
        return ans
```