Skip to content

Commit 727a91f

Browse files
authored
Update maximal-score-after-applying-k-operations.cpp
1 parent 2fd59f3 commit 727a91f

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

C++/maximal-score-after-applying-k-operations.cpp

+28
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,33 @@ class Solution {
99
return (a + b - 1) / b;
1010
};
1111

12+
int64_t result = 0;
13+
make_heap(begin(nums), end(nums));
14+
while (k-- && !empty(nums)) {
15+
int x = nums.front();
16+
result += x;
17+
pop_heap(begin(nums), end(nums)); nums.pop_back();
18+
const auto nx = ceil_divide(x, 3);
19+
if (!nx) {
20+
continue;
21+
}
22+
nums.emplace_back(nx);
23+
push_heap(begin(nums), end(nums));
24+
}
25+
return result;
26+
}
27+
};
28+
29+
// Time: O(n + klogn)
30+
// Space: O(1)
31+
// heap
32+
class Solution2 {
33+
public:
34+
long long maxKelements(vector<int>& nums, int k) {
35+
const auto& ceil_divide = [](const auto& a, const auto& b) {
36+
return (a + b - 1) / b;
37+
};
38+
1239
int64_t result = 0;
1340
make_heap(begin(nums), end(nums));
1441
while (--k >= 0) {
@@ -21,3 +48,4 @@ class Solution {
2148
return result;
2249
}
2350
};
51+

0 commit comments

Comments
 (0)