Simple and Easy C++ code with Detailed explanation || Prefix Sum || Beats 100% ✅ ||Beginner friendly
\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \nThe goal is to calculate the sum of absolute differences between each element in 
![image.png](https://assets.leetcode.com/users/images/a766e44f-ff89-42a3-9890-b55e7d102d9f_1700872862.1521964.png)\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe goal is to calculate the sum of absolute differences between each element in the array and all other elements. To do that:\n1. We can calculate and store the prefix sum of the array of elements.\n2. We can determine the sum of absolute differences of an element with respect to all other elements by applying numeric operations on the prefix sum of the array upto that element and with the total sum of elements of the array.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize a prefix sum array, `preSum`, to store the cumulative sum of elements up to each index.\n2. Calculate the prefix sum array in a single loop to avoid redundant calculations.\n3. Iterate through the array again to compute the sum of absolute differences for each element.\n4. For each element at index i, calculate the left sum (`leftSum`) as the sum of i * nums[i] minus the sum of elements before i. Similarly, calculate the right sum (`rightSum`) as the sum of elements after i minus (n - 1 - i) * nums[i].\n5. Update the element at index i with the sum of `leftSum` and `rightSum`.\nThe modified array now contains the desired sum of absolute differences for each element.\n6. Return the modified array.\n# Complexity\n- Time complexity: O(n)\nThe single loop for calculating the prefix sum array takes O(n) time.\nThe loop for computing the sum of absolute differences also takes O(n) time.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\nAdditional space is used to store the prefix sum array (preSum), resulting in O(n) space complexity.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n    vector<int> getSumAbsoluteDifferences(vector<int>& nums) {\n        ios_base::sync_with_stdio(false);\n        cin.tie(NULL);\n        cout.tie(NULL);\n\n        int n = nums.size();\n        vector<int> preSum(n, 0);\n\n        preSum[0] = nums[0];\n        for (int i = 1; i < n; i++)\n            preSum[i] = preSum[i - 1] + nums[i];\n\n        for (int i = 0; i < n; i++) {\n            int leftSum = i * nums[i] - (i > 0 ? preSum[i - 1] : 0);\n            int rightSum = (preSum[n - 1] - preSum[i]) - (n - 1 - i) * nums[i];\n\n            nums[i] = leftSum + rightSum;\n        }\n\n        return nums;\n    }\n};\n```
['Array', 'Prefix Sum', 'C++']