[Java] Explained - 4ms
Runtime: 4 ms, faster than 62.10% of Java online submissions for Sum of Absolute Differences in a Sorted Array.\nMemory Usage: 50.6 MB, less than 94.76% of Java
Runtime: 4 ms, faster than 62.10% of Java online submissions for Sum of Absolute Differences in a Sorted Array.\nMemory Usage: 50.6 MB, less than 94.76% of Java online submissions for Sum of Absolute Differences in a Sorted Array.\n\n```\nIndex:           0  1  2   3   4\nInout Example:  [1, 4, 6,  8,  10]\nPrefixLeft:     [1, 5, 11, 19, 29]\nPrefixRight:   [29, 28, 24, 18, 10]\n```\n\nWhat we need to do for example number 6 (i=2):\nLeft side:\n\t(6-1) + (6-4)\n\t=> abs(2x6 - (1+4))\n\t=> abs(2x6 - prefixLeft[1])\n\t=> abs((nums[i] x i) - prefixLeft[i-1]))\n\t\nRight side:\n\t(10-6) + (8-6)\n\t=> abs(2x6 - (10+8))\n\t=> abs(2x6 - prefixRight[3]) \n\t=> abs ((nums[i] x (i-nums.length-1)) - prefixRight[i+1])\n\n\n```\nclass Solution {\n    public int[] getSumAbsoluteDifferences(int[] nums) {\n        int n = nums.length;\n        if (n == 0) return nums;\n\n        int[] result = new int[n];\n        int[] prefixLeft = new int[n];\n        int[] prefixRight = new int[n];\n        \n        prefixLeft[0]=nums[0];\n        prefixRight[n-1]=nums[n-1];\n        for(int i=1;i<n;++i) prefixLeft[i] = prefixLeft[i-1] + nums[i];\n        for(int i=n-2;i>=0;--i) prefixRight[i] = prefixRight[i+1] + nums[i];\n \n        for(int i=0;i<n;i++) {\n            int leftSide = 0;\n            int rightSide = 0;\n            if (i>0) leftSide = Math.abs(prefixLeft[i-1] - nums[i]*(i));\n            if (i<n-1) rightSide = Math.abs(prefixRight[i+1] - nums[i]*(n-i-1));\n            result[i] = leftSide+rightSide; \n        }\n       \n        return result;\n        \n    }\n}\n```
[]