-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Agregar sol a sum diferencias absolutas (#10)
- Loading branch information
Diego
committed
Sep 25, 2021
1 parent
d98a1ce
commit 7d0b982
Showing
3 changed files
with
99 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
from typing import List | ||
|
||
|
||
def sum_absolute_differences(nums: List[int]) -> List[int]: | ||
"""Return sum of absolute differences of each element. | ||
For example, if we have the input [2, 3, 5], the result would be: | ||
- result[0] = |2 - 3| + |2 - 5| = 4 | ||
- result[1] = |3 - 2| + |3 - 5| = 3 | ||
- result[2] = |5 - 2| + |5 - 3| = 5 | ||
:param nums: Input array | ||
:type nums: List[int] | ||
:return: Result with sum of absolute differences | ||
:rtype: List[int] | ||
""" | ||
n = len(nums) | ||
prefix = [0]*(n + 1) | ||
for i in range(1, len(nums) + 1): | ||
prefix[i] = prefix[i - 1] + nums[i - 1] | ||
|
||
result = [0]*n | ||
for i in range(n): | ||
result[i] = ( | ||
prefix[n] - prefix[i + 1] - nums[i]*(n - i - 1) | ||
- prefix[i] + nums[i]*i | ||
) | ||
return result |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
from sols.arrays.prefix_sum_problems import sum_absolute_differences | ||
|
||
|
||
def test_sum_absolute_differences(): | ||
assert sum_absolute_differences([2, 3, 5]) == [4, 3, 5] | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters