JAVA Solution
Intuition\nThere are already good solutions posted under solutions section. But I felt there are fewer good java solution. So posting it here.\n\n# Complexity\n
# Intuition\nThere are already good solutions posted under solutions section. But I felt there are fewer good java solution. So posting it here.\n\n# Complexity\n- Time complexity: $$O(mlogn)$$, where m is query length and n is the size of array nums.\n\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution {\n    public List<Long> minOperations(int[] nums, int[] queries) {\n        Arrays.sort(nums);\n        int n = nums.length;\n        long[] pSum = new long[n+1];\n        for(int i=1;i<=n;i++){\n            pSum[i]+=pSum[i-1]+nums[i-1];\n        }\n        List<Long> ans = new ArrayList<>();\n        for(int i=0;i<queries.length;i++){\n            int[] smaller = howManySmaller(nums, queries[i]), \n            larger = howManyGreater(nums, queries[i]);\n            // smaller incs, larger decr\n            long ops = 0;\n            if(smaller[1]!=-1){\n                ops = (long)((long)queries[i]*smaller[0] - pSum[smaller[1]+1]);\n            }\n            if(larger[1]!=-1){\n                ops+= (long)(pSum[n] - pSum[larger[1]] - (long)queries[i]*larger[0]);\n            }\n            ans.add(ops);\n        }\n        return ans;\n    }\n    private int[] howManySmaller(int[] nums, int x){\n        int l = -1, r = nums.length-1;\n        while(l<r){\n            int mid = r+(l-r)/2;\n            if(nums[mid] >= x){\n                r = mid-1;\n            }else{\n                l = mid;\n            }\n        }\n        if(l < 0){\n            return new int[]{0, -1};\n        }\n        return new int[]{l+1, l};\n    }\n    private int[] howManyGreater(int[] nums, int x){\n        int l = 0, r = nums.length;\n        while(l<r){\n            int mid = l+(r-l)/2;\n            if(nums[mid] <= x){\n                l = mid+1;\n            }else{\n                r = mid;\n            }\n        }\n        if(l >= nums.length){\n            return new int[]{0, -1};\n        }\n        return new int[]{nums.length-l, l};\n    }\n        \n}\n// 1 3 6 8\n\n// q = 1\n\n\n```
['Binary Search', 'Sorting', 'Prefix Sum', 'Java']