Seperate Left and Right Sum | Explained | C++ | Java
\n\n\n# Intuition\nSince the array is given to be sorted in increasing order it means that for number at a given index all the numbers in the array to left of i
\n\n\n# Intuition\nSince the array is given to be sorted in increasing order it means that for number at a given index all the numbers in the array to left of it are smaller or equal to it and all the numbers to right of the it are bigger or equal to it.\n\n\n# Approach\nPre requisite: Prefix Sum\n\nFor each number at a given index say \'indx\'\nint leftSum = (indx + 1) * currNumber - (Sum of all numbers till current number);\nint rightSum = (Sum of all numbers after current Number) - (number of numbers after the current Number * current Number)\nresult[indx] = leftSum + rightSum;\n\n\nTo find:\n a)Sum of all numbers till current Number\n b)Sum of all numbers after current Number\n\nin O(1), concept of prefix sum can be applied\n\n# Complexity\n- Time complexity:\nO(n), where n is the size of given nums array\n\n- Space complexity:\nO(n), prefSum computation will require that extra memory, even if we ignore the memory needed for result vector/array\n\n# Code\nC++\n```\nclass Solution {\npublic:\n    vector<int> getSumAbsoluteDifferences(vector<int>& nums) {\n        int sz = nums.size();\n        vector<int> result(sz);\n        vector<long long> prefSum(sz);\n        for(int indx = 0; indx < sz; indx++){\n            if(indx == 0)prefSum[indx] = nums[indx];\n            else prefSum[indx] = prefSum[indx-1] + nums[indx]; \n        }\n        for(int indx = 0; indx < sz; indx++){\n             int currNum = nums[indx];\n             int leftSum = currNum * (indx+1) - prefSum[indx];\n             int rightSum = (prefSum[sz - 1] - prefSum[indx] - (sz - 1 - indx)  * currNum);\n             result[indx] = leftSum + rightSum;\n        }\n        return result;\n    }\n};\n```\nJava\n```\nclass Solution {\n    public int[] getSumAbsoluteDifferences(int[] nums) {\n        int sz = nums.length;\n        int[] result = new int[sz], prefSum = new int[sz];\n        for (int indx = 0; indx < sz; indx++) {\n            if (indx == 0)\n                prefSum[indx] = nums[indx];\n            else\n                prefSum[indx] = prefSum[indx - 1] + nums[indx];\n        }\n        for (int indx = 0; indx < sz; indx++) {\n            int currNum = nums[indx];\n            int leftSum = currNum * (indx + 1) - prefSum[indx];\n            int rightSum = (prefSum[sz - 1] - prefSum[indx] - (sz - 1 - indx) * currNum);\n            result[indx] = leftSum + rightSum;\n        }\n        return result;\n    }\n}\n\n```
['C++', 'Java']