Why to Sort before Prefix sum? Explained
Idea\n Describe your first thoughts on how to solve this problem. \n\n\n- if it\'s neg then -(d-b) lets take this as eg. like b > d.\n- then d-a + d-b + d-c = 3
# Idea\n<!-- Describe your first thoughts on how to solve this problem. -->\n![CapturedImage-17-06-2023 18-01-11.png](https://assets.leetcode.com/users/images/133addb5-fb43-40d0-a877-6112eb9f78c4_1687005206.596571.png)\n\n- if it\'s neg then -(d-b) lets take this as eg. like b > d.\n- then d-a + d-b + d-c = 3d - (a+b+c) cannot be done.\n\n# Complexity\n- Time complexity:$$O(N + NLogN + N)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n    int sumDistance(vector<int>& nums, string s, int d) {\n        int N = nums.size();\n        for(int i=0; i<N; i++){\n            if(s[i] == \'L\')\n                nums[i] -= d;\n            else\n                nums[i] += d; \n        }\n\n        long long ans = 0;\n        int mod = 1e9 + 7;\n        long long preSum = 0;\n        sort(nums.begin(), nums.end());\n\n        for(int i=0; i<N; i++){\n            ans = (ans + i*(long long)nums[i] - preSum)%mod;\n            preSum = (preSum + nums[i])%mod;\n        }\n\n        return (int)ans;\n    }\n};\n```
['C++']