3
long long minimalKSum(vector<int> &nums, int k) {6
// Sort array so that we can get smaller elements first7
sort(begin(nums), end(nums));11
// Previous element that we encountered12
int prev = 0, curr = 0;14
for (int i = 0; i < n; i++) {17
// Get the difference b/w prev and current18
// So that we can append elements that are in between them19
long long diff = (curr - prev - 1);21
// If prev and current are same then just skip27
// If there are more available elements b/w prev and current28
// Then we just take closest k element from prev.29
// And leave remaining as it is35
// Get the sum of all elements b/w prev and current36
// Since it is AP series, we can use direct formula37
sum += (diff * 1LL * (curr + prev) / 2);39
// Update previous to current42
// Update count of how many more element we need to append48
// Case : When we have reached the end of array49
// And still we have some more element left to append51
sum += (k * 1LL * (2 * prev + k + 1) / 2);