[LeetCode] Maximal Score After Applying K Operations

2530. Maximal Score After Applying K Operations

You are given a 0-indexed integer array nums and an integer k. You have a starting score of 0.

In one operation:

  1. choose an index i such that 0 <= i < nums.length,
  2. increase your score by nums[i], and
  3. replace nums[i] with ceil(nums[i] / 3).

Return the maximum possible score you can attain after applying exactly k operations.

The ceiling function ceil(val) is the least integer greater than or equal to val.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
long long maxKelements(vector<int>& nums, int k) {
long long res = 0;
priority_queue<int> q;
for(auto n : nums) q.push(n);
while(k) {
if(q.top() == 1) return res + k;
else {
k -= 1;
long long tp = q.top(); q.pop();
res += tp;
q.push((tp + 2) / 3);
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/02/07/PS/LeetCode/maximal-score-after-applying-k-operations/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.