Optimal Approach || Prefix Sum || Binary Search || Fully Explained Approach || O(N * log N) || C++
Approach\n- We want to make all the numbers equal to x.\n- There can be two types of numbers in the array ->\n  1. that are <= x (Type 1)\n  2. that are > x (Ty
# Approach\n- We want to make all the numbers equal to $$x$$.\n- There can be two types of numbers in the array ->\n  1. that are $$<= x$$ (Type 1)\n  2. that are $$> x$$ (Type 2)\n- For numbers of **type 1** $$(<=x)$$, we would increase their value to make them equal to $$x$$.\n Suppose there are $$a$$ numbers that are $$<=x$$. The operations required to change all these numbers to $$x$$ will be $$a*x$$ $$-$$ $$(sum$$ $$of$$ $$all$$ $$these$$ $$numbers) $$ \n\n\n\n- For numbers of **type 2** $$(>x)$$, we would decrease their value to make them equal to $$x$$.\n Suppose there are $$b$$ numbers that are $$>x$$. The operations required to change all these numbers to $$x$$ will be $$(sum$$ $$of$$ $$all$$ $$these$$ $$numbers)$$ $$-$$ $$b*x$$  \n\n- **Note-** We can find sum in O(1) by using prefix array.\n\n- The total number of operations would be the sum of operations of both.\n\nFor example, nums = [3,1,6,8], queries = [1,5]\n\n![parth lc 2602 soln.jpg](https://assets.leetcode.com/users/images/8fab782c-c990-4ea4-8f65-727bbed120a9_1679808299.6859477.jpeg)\n\n\n# Complexity\n- Time complexity : $$O(N * log N)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity : $$O(N)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n#define ll long long\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\n        vector<ll> pre(n,0);\n        pre[0]=1ll*nums[0];\n        for(int i=1 ; i<n ; i++) pre[i]=pre[i-1]+1ll*nums[i];\n        \n        vector<ll> ans;\n        for(int q:queries) {\n            auto it = --upper_bound(nums.begin(),nums.end(),q);\n            int i = it - nums.begin();\n            \n            long long x = (i<0) ? 0 : (1ll*(i+1)*q - pre[i]);\n            long long y = (i<0) ? (pre[n-1] - 1ll*n*q) : (pre[n-1] - pre[i] - 1ll*(n-i-1)*q);\n            \n            ans.push_back(x+y);\n        }\n        return ans;\n    }\n};\n```\n\n## Do let me know if you have any doubt in the solution\u2714.\n## Please upvote\uD83D\uDD3C if you liked the solution\n## \uD83D\uDCBB\uD83D\uDC31\u200D\uD83D\uDCBBIf there are any suggestions / questions / mistakes in my post, please do comment below \uD83D\uDC47\n\n![e2515d84-99cf-4499-80fb-fe458e1bbae2_1678932606.8004954.png](https://assets.leetcode.com/users/images/945d1086-e6fa-418c-b9db-f0ffe3083328_1679817112.9945686.png)\n\n\n\n\n
['Binary Search', 'Prefix Sum', 'C++']