[LeetCode] Append K Integers With Minimal Sum

2195. Append K Integers With Minimal Sum

You are given an integer array nums and an integer k. Append k unique positive integers that do not appear in nums to nums such that the resulting total sum is minimum.

Return the sum of the k integers appended to nums

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
long long minimalKSum(vector<int>& nums, int k) {
set<long long> num(nums.begin(), nums.end());
long long find = 1, prev = 0;
long long sum = 0;

for(long long n : num) {
if(find == n) find++;
else {
if(n - 1 - prev <= k) {
sum += (n) * (n-1) / 2 - (prev) * (prev + 1) / 2;
k -= (n - 1 - prev);
} else {
sum += (prev + k) * (prev + k + 1) / 2 - (prev) * (prev + 1) / 2;
k = 0;
}
find = n + 1;
}
prev = n;
if(!k) break;
}
if(k)
sum += (prev + k) * (prev + k + 1) / 2 - (prev) * (prev + 1) / 2;
return sum;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/06/PS/LeetCode/append-k-integers-with-minimal-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.