File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments