Leetcode 1787 Solution
This article provides solution to leetcode question 1787 (sum-of-absolute-differences-in-a-sorted-array)
Access this page by simply typing in "lcs 1787" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/sum-of-absolute-differences-in-a-sorted-array
Solution
class Solution:
def getSumAbsoluteDifferences(self, nums: List[int]) -> List[int]:
n = len(nums)
s1 = [0] * n
s2 = [0] * n
s = 0
for i, num in enumerate(nums):
s += num
s1[i] = s
s = 0
for i, num in enumerate(list(reversed(nums))):
s += num
s2[n - 1 - i] = s
ans = []
for i, num in enumerate(nums):
left_sum = i * num - s1[i - 1] if i > 0 else 0
right_sum = s2[i + 1] - (n - 1 - i) * num if i < n - 1 else 0
ans.append(left_sum + right_sum)
return ans