Java | Sorting | with explanation
The logic behind : i*arr[i] - (n-1-i)*arr[i] in calculating Sum of absolute differences of all pairs in a given array:\n\nLet\'s take an example: [1,2,3,4,5] (A
### The logic behind : `i*arr[i] - (n-1-i)*arr[i]` in calculating Sum of absolute differences of all pairs in a given array:\n\nLet\'s take an example: [1,2,3,4,5] (After Sorting) (n = no. of elements = 5)\n\nSum of absolute differences of all pairs in a given array:\n\n(2-1) + (3-1) + (4-1) + (5-1) +\n(3-2) + (4-2) + (5-2) +\n(4-3) + (5-3) + \n(5-4)\n\n= 20\n\nWe can write it as:\n\n1x0 + (-1x4) +\n2x1 + (-2x3) +\n3x2 + (-3x2) +\n4x3 + (-4x1) +\n5x4 + (-5x0) \n\nwhich is equal to \n\n1x0 - (1x4) +    `(i=0 , n-1-i = 4)`\n2x1 - (2x3) +    `(i=1 , n-1-i = 3)`\n3x2 - (3x2) +    `(i=2 , n-1-i = 2)`\n4x3 - (4x1) +    `(i=3 , n-1-i = 1)`\n5x4 - (5x0)     `(i=4 , n-1-i = 0)`\n\nresulting in 20\n\n## Complexity\n- Time complexity: O(nlogn)\n\n- Space complexity: O(1)\n\n## Code\n``` java []\nclass Solution {\n    static int mod = (int)(1e9 + 7);\n    public int sumDistance(int[] arr, String s, int d) {\n        int n = arr.length;\n        \n        for(int i=0;i<n;i++){\n            if(s.charAt(i)==\'R\'){\n                arr[i]+=d;\n            }\n            else{\n                arr[i]-=d;\n            }\n        }\n\n        Arrays.sort(arr);\n\n        long sum = 0;\n        \n        for(int i = 0; i < n; i++) {\n            sum = (sum + i*(long)arr[i] - (n-1-i)*(long)arr[i])%mod;\n        }\n \n        return (int)sum;\n    }\n}\n```
['Sorting', 'Java']