Skip to content

1685. Sum of Absolute Differences in a Sorted Array 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
 public:
  vector<int> getSumAbsoluteDifferences(vector<int>& nums) {
    const int n = nums.size();
    vector<int> ans;
    // prefix[i] := sum(nums[0..i])
    vector<int> prefix(n);
    // suffix[i] := sum(nums[i..n - 1])
    vector<int> suffix(n);

    prefix[0] = nums[0];
    for (int i = 1; i < n; ++i)
      prefix[i] = prefix[i - 1] + nums[i];

    suffix[n - 1] = nums[n - 1];
    for (int i = n - 2; i >= 0; --i)
      suffix[i] = suffix[i + 1] + nums[i];

    for (int i = 0; i < nums.size(); ++i) {
      const int left = nums[i] * (i + 1) - prefix[i];
      const int right = suffix[i] - nums[i] * (n - i);
      ans.push_back(left + right);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
  public int[] getSumAbsoluteDifferences(int[] nums) {
    final int n = nums.length;
    int[] ans = new int[n];
    int[] prefix = new int[n];
    int[] suffix = new int[n];

    prefix[0] = nums[0];
    for (int i = 1; i < n; ++i)
      prefix[i] = prefix[i - 1] + nums[i];

    suffix[n - 1] = nums[n - 1];
    for (int i = n - 2; i >= 0; --i)
      suffix[i] = suffix[i + 1] + nums[i];

    for (int i = 0; i < nums.length; ++i) {
      final int left = nums[i] * (i + 1) - prefix[i];
      final int right = suffix[i] - nums[i] * (n - i);
      ans[i] = left + right;
    }

    return ans;
  }
}
1
2
3
4
5
6
class Solution:
  def getSumAbsoluteDifferences(self, nums: list[int]) -> list[int]:
    prefix = list(itertools.accumulate(nums))
    suffix = list(itertools.accumulate(nums[::-1]))[::-1]
    return [num * (i + 1) - prefix[i] + suffix[i] - num * (len(nums) - i)
            for i, num in enumerate(nums)]