• + 0 comments

    O(n* log(n)), the actual algo takes O(n) time, but it requires packets to be sorted, which takes n*log(n)

    long angryChildren(int k, vector<long> packets) {
        long L = 0, current = 0;
        vector<long> partialSum = {0};
        sort(packets.begin(), packets.end());
        for (int x : packets) partialSum.push_back(partialSum.back() + x);
        for (int i=1; i < k; i++) current = current + i * packets[i] - partialSum[i];
        L = current;
        for (int i=1; i <= packets.size()-k; i++) {
            current = current + (k-1) * (packets[i+k-1] + packets[i-1]) - 2 * (partialSum[i+k-1] - partialSum[i]);
            L = min(L, current);
        }
        return L;
    }