Swift | Prefix Sum + Binary Search
Prefix Sum + Binary Search (accepted answer)\n\nclass Solution {\n    func minOperations(_ nums: [Int], _ queries: [Int]) -> [Int] {\n        let nums = nums.so
**Prefix Sum + Binary Search (accepted answer)**\n```\nclass Solution {\n    func minOperations(_ nums: [Int], _ queries: [Int]) -> [Int] {\n        let nums = nums.sorted()\n        let prefixSums = nums.reduce(into: [0]) { $0.append($1 + $0.last!) }\n        \n        return queries.map { q in \n            var (left, right) = (0, nums.count)\n            while left < right {\n                let mid = (left+right)/2\n                (left, right) = nums[mid] > q ? (left, mid) : (mid+1, right)\n            }\n            let totalAmountBelowAverage = q * left - prefixSums[left]\n            let totalAmountAboveAverage = prefixSums.last! - prefixSums[left] - q * (nums.count - left) \n            return totalAmountBelowAverage + totalAmountAboveAverage\n        }\n    }\n}\n```
['Swift']