Faster || Easy To Understand || C++ Code
Approach 1 : Using Prefix Sum\n\n Time Complexity : O(N)\n Space Complexity : O(N)\n\n\nclass Solution {\npublic:\n    vector<int> getSumAbsoluteDifferences(vec
* ***Approach 1 : Using Prefix Sum***\n\n* ***Time Complexity : O(N)***\n* ***Space Complexity : O(N)***\n\n```\nclass Solution {\npublic:\n    vector<int> getSumAbsoluteDifferences(vector<int>& nums) {\n        \n        int n = nums.size();\n        \n        vector<int> res(n);\n        \n        vector<int> prefix(n, 0);\n        \n        prefix[0] = nums[0];\n        \n        for(int i = 1; i < n; i++)\n        {\n            prefix[i] = prefix[i - 1] + nums[i];\n        }\n        \n        for(int i = 0; i < n; i++)\n        {\n            int left = 0;\n            \n            if(i > 0)\n            {\n                left = prefix[i - 1];\n            }\n            \n            left -= i * nums[i];\n            \n            int right = 0;\n            \n            right = prefix[n - 1] - prefix[i] - (n - 1 - i) * nums[i];\n            \n            int temp = right - left;\n            \n            res[i] = temp;\n        }\n        \n        return res;\n    }\n};\n```\n\n\n* ***Approach 2 : Space Optimized***\n\n* ***Time Complexity : O(N)***\n\n* ***Space Complexity : O(1)***\n\n```\nclass Solution {\npublic:\n    vector<int> getSumAbsoluteDifferences(vector<int>& nums) {\n        \n        int n = nums.size();\n        \n        vector<int> res(n);\n        \n        int total_sum = 0;\n        \n        for(auto x : nums)\n        {\n            total_sum += x;\n        }\n        \n        int left_sum = 0;\n        \n        int right_sum = 0;\n        \n        for(int i = 0; i < n; i++)\n        {\n            left_sum += nums[i];\n            \n            right_sum = total_sum - left_sum;\n            \n            int left = left_sum - (i + 1) * nums[i];\n            \n            int right = right_sum - (n - 1 - i) * nums[i];\n            \n            int temp = right - left;\n            \n            res[i] = temp;\n        }\n        \n        return res;\n    }\n};\n```
['C', 'Prefix Sum']