-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1685.getSumAbsolutteDifferences.py
62 lines (41 loc) · 1.59 KB
/
1685.getSumAbsolutteDifferences.py
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
"""
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).
Example 1:
Input: nums = [2,3,5]
Output: [4,3,5]
Explanation: Assuming the arrays are 0-indexed, then
result[0] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4,
result[1] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3,
result[2] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5.
Example 2:
Input: nums = [1,4,6,8,10]
Output: [24,15,13,15,21]
Constraints:
2 <= nums.length <= 105
1 <= nums[i] <= nums[i + 1] <= 104
"""
from typing import List
class Solution:
def getSumAbsoluteDifferences(self, nums: List[int]) -> List[int]:
# get total sum, for later subtraction
total_sum = sum(nums)
# left sum start at index 0 so sum of 0
left_sum = 0
res = []
# loop array, get the right rum
for i, n in enumerate(nums):
right_sum = total_sum - n - left_sum
left_size, right_size = i, len(nums) - i - 1
# NOTE: calculate the absolute differences
res.append(
# taking the left subarray, subtract left sum
(left_size * n - left_sum)
+
# right_sum
(right_sum - right_size * n)
)
# update left sum
left_sum += n
return res