from ABC186 ABC186D image

  • image
  • D - Sum of difference
  • There is a lot of talk on Twitter about using cumulative sums, but I don’t use cumulative sums.
  • If you sort and take the difference between adjacent terms and let Di be the number of occurrences of Di in the solution is i(N-i), so just multiply and add.
    • image
    • python
def main():
    N = int(input())
    AS = list(map(int, input().split()))
    AS.sort()
    DS = []
    for i in range(N - 1):
        DS.append(AS[i + 1] - AS[i])
    ret = 0
    for i in range(N - 1):
        ret += DS[i] * (N - 1 - i) * (i + 1)
    print(ret)

This page is auto-translated from /nishio/ABC186D using DeepL. If you looks something interesting but the auto-translated English is not good enough to understand it, feel free to let me know at @nishio_en. I’m very happy to spread my thought to non-Japanese readers.