You are given an integer array nums sorted in non-decreasing order.
Build and return an integer array result with the same length as nums such that result[i] is equal to the summation of absolute differences between nums[i] and all the other elements in the array.
In other words, result[i] is equal to sum(|nums[i]-nums[j]|) where 0 <= j < nums.length and j != i (0-indexed).
First, we calculate the sum of all elements in the array $nums$, denoted as $s$. We use a variable $t$ to record the sum of the elements that have been enumerated so far.
Next, we enumerate $nums[i]$. Then $ans[i] = nums[i] \times i - t + s - t - nums[i] \times (n - i)$. After that, we update $t$, i.e., $t = t + nums[i]$. We continue to enumerate the next element until all elements are enumerated.
The time complexity is $O(n)$, where $n$ is the length of the array $nums$. The space complexity is $O(1)$.
classSolution{publicint[]getSumAbsoluteDifferences(int[]nums){// int s = Arrays.stream(nums).sum();ints=0,t=0;for(intx:nums){s+=x;}intn=nums.length;int[]ans=newint[n];for(inti=0;i<n;++i){intv=nums[i]*i-t+s-t-nums[i]*(n-i);ans[i]=v;t+=nums[i];}returnans;}}