Skip to content

2530. Maximal Score After Applying K Operations 👍

  • Time: $O(n\log k)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  long long maxKelements(vector<int>& nums, int k) {
    long ans = 0;
    priority_queue<int> maxHeap;

    for (const int num : nums)
      maxHeap.push(num);

    for (int i = 0; i < k; ++i) {
      const int num = maxHeap.top();
      maxHeap.pop();
      ans += num;
      maxHeap.push((num + 2) / 3);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public long maxKelements(int[] nums, int k) {
    long ans = 0;
    Queue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());

    for (final int num : nums)
      maxHeap.offer(num);

    for (int i = 0; i < k; ++i) {
      final int num = maxHeap.poll();
      ans += num;
      maxHeap.offer((num + 2) / 3);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def maxKelements(self, nums: list[int], k: int) -> int:
    ans = 0
    maxHeap = [-num for num in nums]
    heapq.heapify(maxHeap)

    for _ in range(k):
      num = -heapq.heappop(maxHeap)
      ans += num
      heapq.heappush(maxHeap, -math.ceil(num / 3))

    return ans