Magical Formula lol | O(nlogn) | Binary Search | Prefix Sum
// Intuition behind this is to isolate numbers less than queries[i] and number greater or equal to queries[i]  and then perform this magical formula\n    // ans
// Intuition behind this is to isolate numbers less than queries[i] and number greater or equal to queries[i]  and then perform this magical formula\n    // ans[i] = (idx*x-res[idx-1]) + res[n-1]-res[idx-1]-x*n-idx  --> key formula I derived (all terms are used in code)\n\t// 1,3,6,8   \n    // 1,4,10,18  -> prefix sum array\n    // check for 5\n    // lower bound of 5 will give us index 2\n\t// Then apply this formula, think of it and you will get to know why I isolated numbers greater than queries[i] and less than queries[i] seprately\n    \n\t\n\t\n\t\tclass Solution {\n\t\tpublic:\n\t\t\t\tvector<long long> minOperations(vector<int>& nums, vector<int>& queries) {\n\t\t\t\tsort(nums.begin(),nums.end());\n\t\t\t\tint n =nums.size();\n\t\t\t\tvector<long long> sumarray(n);\n\t\t\t\tlong long sum=0;\n\t\t\t\tfor(int i=0;i<n;i++){\n\t\t\t\t\tsum+=nums[i];\n\t\t\t\t\tsumarray[i] = sum;\n\t\t\t\t}\n\t\t\t\tlong long q = queries.size();\n\t\t\t\tvector<long long> ans(q);\n\t\t\t\tfor(int i=0;i<q;i++){\n\t\t\t\t\tlong long x = queries[i];\n\t\t\t\t\tlong long idx = lower_bound(nums.begin(),nums.end(),x)-nums.begin();\n\t\t\t\t\tif(idx == 0 || idx == n ) ans[i] = abs(n*x - sumarray[n-1] );\n\t\t\t\t\telse ans[i] = (idx*x - sumarray[idx-1] ) + sumarray[n-1]-sumarray[idx-1]-x*(n-idx);\n\t\t\t\t}\n\t\t\t\treturn ans;\n\t\t\t}\n\t\t};
['Binary Search', 'C', 'Prefix Sum']