Skip to content

Commit 0738036

Browse files
authored
Create append-k-integers-with-minimal-sum.cpp
1 parent f0c4ccf commit 0738036

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// Time: O(nlogn)
2+
// Space: O(n)
3+
4+
// greedy
5+
class Solution {
6+
public:
7+
long long minimalKSum(vector<int>& nums, int k) {
8+
int64_t result = static_cast<int64_t>(k) * (k + 1) / 2, curr = k + 1;
9+
for (const auto& x : set<int>(cbegin(nums), cend(nums))) {
10+
if (x < curr) {
11+
result += curr++ - x;
12+
}
13+
}
14+
return result;
15+
}
16+
};
17+
18+
// Time: O(nlogn)
19+
// Space: O(n)
20+
// greedy
21+
class Solution2 {
22+
public:
23+
long long minimalKSum(vector<int>& nums, int k) {
24+
int64_t result = 0, prev = 0;
25+
nums.emplace_back(numeric_limits<int>::max());
26+
for (const auto& x : set<int>(cbegin(nums), cend(nums))) {
27+
if (!k) {
28+
break;
29+
}
30+
const int cnt = min((x - 1) - prev, static_cast<int64_t>(k));
31+
k -= cnt;
32+
result += ((prev + 1) + (prev + cnt)) * cnt / 2;
33+
prev = x;
34+
}
35+
return result;
36+
}
37+
};

0 commit comments

Comments
 (0)