Maximal Score After Applying K Operations

Pop the max k times, halving it each pop — max-heap with simulated operations.

Medium
Time O((n + k) log n) Space O(n)
LeetCode
4 min read
top-k heaps greedy

Problem#

In one operation, pop the largest element of nums, add it to the score, then push back ceil(x / 3). After k operations, return the max score.

Examples#

  • nums = [10,10,10,10,10], k = 550
  • nums = [1,10,3,3,3], k = 317

Constraints#

  • 1 <= nums.length, k <= 10^5.

Approach#

Max-heap. Pop k times, accumulate, push ceil(top / 3).

Solution#

Maximal Score After K Ops
class Solution {
public:
long long maxKelements(vector<int>& nums, int k) {
priority_queue<long long> pq(nums.begin(), nums.end());
long long score = 0;
while (k--) {
long long x = pq.top(); pq.pop();
score += x;
pq.push((x + 2) / 3); // ceiling division
}
return score;
}
};

Editorial#

Greedy is optimal because each operation contributes x to the score independent of the order. So picking the max at each step maximizes the immediate gain, and the reduced (ceil(x/3)) version will still be available for future picks.

Complexity#

  • Time: O((n + k) log n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.