Sort | Binary Search
Intuition\nBrute force will give TLE. Look for a pivot from where either we only need to increment or decrement.\n\n# Approach\nCarefully note that the answer d
# Intuition\nBrute force will give TLE. Look for a pivot from where either we only need to increment or decrement.\n\n# Approach\nCarefully note that the answer does not depend on the order of the elements. In such a case, we can utilize binary search to identify a pivot 1) before which all elements are smaller 2) after which all elements are bigger. For binary, we first need to sort it.\nOnce completed, our answer will be sum of both the above cases using pattern.\n\n# Complexity\n- Time complexity: $$O(mlog(n))$$ , where m is no. of queries.\n\n# Code\n```\nclass Solution {\npublic:\n    vector<long long> minOperations(vector<int>& nums, vector<int>& queries) {\n        sort(nums.begin(), nums.end());\n        int n = nums.size();\n        vector<long long> prefix(n + 1);\n        for (int i=0;i<n;++i) {\n            prefix[i+1] = prefix[i] + (long long)nums[i];\n        }\n        vector<long long> ans;\n        for (auto &query : queries) {\n            int left = 0, right = n;\n            while (left < right) {\n                int mid = left + (right - left) / 2;\n                if (query < nums[mid]) {\n                    right = mid;\n                }\n                else {\n                    left = mid + 1;\n                }\n            }\n            long long inc = (long long)query * left - prefix[left];\n            long long dec = prefix[n] - prefix[left] - (long long)query * (n - left);\n            ans.push_back(inc + dec);\n        }\n        return ans;        \n    }\n};\n```
['Binary Search', 'Sorting', 'C++']