OIG VIII - dziwne

// https://szkopul.edu.pl/problemset/problem/dwc/site/?key=statement
// VIII OIG — Zawody drużynowe, etap I, runda II.

#include <algorithm>
#include <cstdint>
#include <iostream>
#include <limits.h>

constexpr int sizik = 1000 * 1001;

long long suff[sizik], tab[sizik];

int main() {
    std::ios_base::sync_with_stdio(0);
    std::cin.tie(0);
    std::cout.tie(0);

    int n, k;
    std::cin >> n >> k;

    for (int i = 1; i <= n; i++) {
        std::cin >> tab[i];
    }

    std::sort(tab + 1, tab + 1 + n);

    tab[n + 1] = INT64_MAX - 2ll * INT32_MAX;

    for (int i = n; i >= 0; i--) {
        suff[i] = tab[i];
        suff[i] += suff[i + 1];
    }

    int pptr = 1;
    long long ans = 0;

    for (int i = 1; i < n; i++) {
        while (tab[pptr + 1] - tab[i] <= k && pptr < n + 1) {
            pptr++;
        }

        ans += (long long)(pptr - i) * k;

        ans += suff[pptr + 1] - tab[i] * (n - pptr);
    }

    std::cout << ans << '\n';

    return 0;
}