forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
maximal-score-after-applying-k-operations.cpp
51 lines (46 loc) · 1.28 KB
/
maximal-score-after-applying-k-operations.cpp
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Time: O(n + klogn)
// Space: O(1)
// heap
class Solution {
public:
long long maxKelements(vector<int>& nums, int k) {
const auto& ceil_divide = [](const auto& a, const auto& b) {
return (a + b - 1) / b;
};
int64_t result = 0;
make_heap(begin(nums), end(nums));
while (k-- && !empty(nums)) {
int x = nums.front();
result += x;
pop_heap(begin(nums), end(nums)); nums.pop_back();
const auto nx = ceil_divide(x, 3);
if (!nx) {
continue;
}
nums.emplace_back(nx);
push_heap(begin(nums), end(nums));
}
return result;
}
};
// Time: O(n + klogn)
// Space: O(1)
// heap
class Solution2 {
public:
long long maxKelements(vector<int>& nums, int k) {
const auto& ceil_divide = [](const auto& a, const auto& b) {
return (a + b - 1) / b;
};
int64_t result = 0;
make_heap(begin(nums), end(nums));
while (--k >= 0) {
int x = nums.front();
result += x;
pop_heap(begin(nums), end(nums)); nums.pop_back();
nums.emplace_back(ceil_divide(x, 3));
push_heap(begin(nums), end(nums));
}
return result;
}
};