2530 Maximal Score After Applying Operations
Problem Statement
You are given a 0-indexed integer array nums
and an integer k
. You have a starting score of 0
.
Instructions
In one operation:
choose an index
i
such that0 <= i < nums.length
,increase your score by
nums[i]
, andreplace
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 toval
.
For the whole problem statement, please refer here.
Plans
Use a max-heap to efficiently retrieve the maximum element in nums for every operation.
Perform exactly k operations:
In each operation, pop (remove) the maximum element from the heap.
Increase the score by the popped element.
Compute the new value after applying the ceiling division by 3 and push it back to the heap.
Return the final score after completing k operations.
Solution
Explanation
Max-Heap Initialization
Sice Python's
heapq
implements a min-heap, negate the elements ofnums
to simulate a max-heap. This allows us to always retrieve the larget element easily.
Score Calculation
Initialize the score to 0.
Perform the k operations in each iteration:
Pop the maximum element from the heap and negate it back to get the original value.
Add the popped element to the score.
Compute the new value after applying the ceiling division by333.
Inserting New Value
After calculating the new value, push it back to the max-heap by negating it.
Return the Final Score
After completing
k
operations, return the final score which holds the maximum possible score after applying exactlyk
operations.
Last updated