나는 이렇게 학습한다/Algorithm & SQL

0923. Sum of differences in array

daco2020 2022. 9. 23. 23:32
반응형

Your task is to sum the differences between consecutive pairs in the array in descending order.

Example

[2, 1, 10]  -->  9

In descending order: [10, 2, 1]

Sum: (10 - 2) + (2 - 1) = 8 + 1 = 9

If the array is empty or the array has only one element the result should be 0 (Nothing in Haskell, None in Rust).



Solution:

def sort(func):
    def wrapper(arr):
        return func(sorted(arr, reverse=True))
    return wrapper

@sort
def sum_of_differences(arr):
    return sum(i - j for i, j in zip(arr, arr[1:]))


반응형