prefix sum
Approach\nWe build a prefix sum of differences so we can tell in constant time how many operations needed for sub array for a query\n \nexample:  [1,3,4, 6, 8]\
# Approach\nWe build a prefix sum of differences so we can tell in constant time how many operations needed for sub array for a query\n ```\nexample:  [1,3,4, 6, 8]\n prefix:    0 2 5 10  17\n```\nwe build posfix sum difference as well in order to tell in O(1) time amount of operations needed from left to right indexes\nThen we run binary search to find a splitting index for a query and run a calculation   \n\n# Complexity\n- Time complexity:\n$$O(NLogM)$$ N-size of queries, M-size of nums\n\n- Space complexity:\n$$O(2n)$$\n\n# Code\n```           \nvar minOperations = function(nums, queries) {\n    nums.sort((a,b)=>a-b);\n    const pref=[0], post=Array(nums.length).fill().map(v=>0);\n    \n    for(let i=1;i<nums.length;i++){\n        pref[i]=pref[i-1]+(nums[i]-nums[0]);\n    }\n\n    for(let i=nums.length-2;i>=0;i--){\n        post[i]=post[i+1]+(nums[nums.length-1]-nums[i]);\n    }\n    \n    // get total operations from left to right\n    const getOpsPref=(l,r,q)=>{\n        if(l>r) return 0;\n        const pivot = q-nums[0];\n        return pivot+( (pivot*r) - pref[r]);\n    }\n\n    // get total operations from right to left\n    const getOpsPost=(l,r,q)=>{\n        if(l>r) return 0;\n        const pivot = Math.abs(q-nums[nums.length-1]);\n        return pivot+( (pivot*(r-l)) - post[l]);\n    }\n\n    let ans=[];\n\n    // Binary search\n    for(const q of queries){\n        let l=0, r=nums.length-1, split=-1;\n        while(l<=r){\n            const mid=Math.trunc((l+r)/2);\n            if(nums[mid]<=q){\n                split=mid;\n                l=mid+1;\n            }else{\n                r=mid-1;\n            }\n        }\n        const leftOperations = getOpsPref(0,split,q);\n        const rightOperations = getOpsPost(split+1,nums.length-1,q);\n        ans.push(leftOperations+rightOperations);\n    }\n\n    return ans;\n};\n```
['JavaScript']