Sorting+Prefix Sum + Binary Search
Intuition\nIntuition is we need to make all element equal to given target and there is time constraint to we need to think like number of elements that are goin
# Intuition\nIntuition is we need to make all element equal to given target and there is time constraint to we need to think like number of elements that are going to be increase i.e number which is less than target and decrease the number which is greater than the target.\n\n# Approach\nAs going on each index will lead to TLE so to optimize this ,sort the array and now we can find index till that we need to increase and after that we need to decrease.For this purpose I used lower bound.Now to count the step I use prefix sum .To avoid runtime error ,use long long.\n\n# Complexity\n- Time complexity:\nO(n*log(n))-for sorting\nO(n)-for prefix sum\nO(n*(log(n)))-for quering \n\n- Space complexity:\nO(n)-for prefix sum\n\n# Code\n```\nclass Solution {\npublic:\n    vector<long long> minOperations(vector<int>& nums, vector<int>& queries) {\n        int n=nums.size();\n        vector<long long >ans;\n      sort(nums.begin(),nums.end());\n        vector<long long >prefix(n);\n        prefix[0]=nums[0];\n        for(int i=1;i<n;i++)prefix[i]=nums[i]+prefix[i-1];\n      \n        for(auto x:queries)\n        {\n          long long  target=x;\n          long long  l=0,h=n-1;\n          long long idx=lower_bound(nums.begin(),nums.end(),target)-nums.begin();\n          if(idx<n)\n          {\n            if(nums[idx]>target )idx--;\n          }\n          else idx--;\n          \n          // cout<<idx<<endl;\n          if(idx<0)\n          {\n            long long rest=prefix[n-1]-(n)*target;\n          ans.push_back(rest);\n          }\n          else\n          {\n            long long cnt=(idx+1)*(1ll)*target-prefix[idx];\n          long long rest=prefix[n-1]-prefix[idx]-(n-idx-1)*target;\n          long long res=cnt+rest;\n          ans.push_back(res);\n          }\n          \n        }\n      return ans;\n    }\n};\n```
['Binary Search', 'Sorting', 'Prefix Sum']