Maximal Score After Applying K Operations Problem
#2530
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2530.
You are given a 0-indexed integer array nums and an integer k. You have a starting score of 0.
In one operation:
- choose an index
isuch that0 <= i < nums.length, - increase your score by
nums[i], and - replace
nums[i]withceil(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.
Example 1:
Input: nums = [10,10,10,10,10], k = 5
Output: 50
Explanation: Apply the operation to each array element exactly once. The final score is 10 + 10 + 10 + 10 + 10 = 50.
Example 2:
Input: nums = [1,10,3,3,3], k = 3
Output: 17
Explanation: You can do the following operations:
Operation 1: Select i = 1, so nums becomes [1,4,3,3,3]. Your score increases by 10.
Operation 2: Select i = 1, so nums becomes [1,2,3,3,3]. Your score increases by 4.
Operation 3: Select i = 2, so nums becomes [1,2,1,3,3]. Your score increases by 3.
The final score is 10 + 4 + 3 = 17.
Constraints:
1 <= nums.length, k <= 10^51 <= nums[i] <= 10^9
Solution
Approach: Max Heap
Each operation adds nums[i] to the score and replaces it with ceil(nums[i] / 3), so the best move is always to take the current largest element. Keep all numbers in a max heap; k times, pop the largest v, add it to the score and push back ceil(v / 3), which equals (v + 2) / 3 in integer arithmetic.
Complexity: O(n + k log n) time and O(n) space.
from heapq import heapify, heappop, heappush
from math import ceil
class Solution:
def maxKelements(self, nums: List[int], k: int) -> int:
h = [-v for v in nums]
heapify(h)
ans = 0
for _ in range(k):
v = -heappop(h)
ans += v
heappush(h, -(ceil(v / 3)))
return ans