Problem
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.
Examples
Example 1:
| |
Example 2:
| |
Solution
Method 1 - Using MaxHeap
To achieve the maximum possible score after exactly k operations, you should focus on repeatedly selecting the largest possible values from nums as it will give the highest immediate score increments. Once a value is selected, it should be replaced by ceil(value / 3) to potentially be reused in subsequent operations, albeit with a reduced value.
Here is the approach:
- Use a Max-Heap:
- Max-Heap is essential here because it allows us to always pick the largest element efficiently. In Python, the
heapqmodule provides a min-heap, so we’ll need to insert negative values to simulate a max-heap behavior. - For Java, a
PriorityQueueconfigured with a custom comparator can serve as a max-heap.
- Max-Heap is essential here because it allows us to always pick the largest element efficiently. In Python, the
- Initialization:
- Initialize the max-heap with all the elements from
numsusing their negative values for Python and natural ordering for Java to mimic a max-heap. - Maintain a variable,
score, to accumulate the score from each operation.
- Initialize the max-heap with all the elements from
- Operations:
- For each of the
koperations, extract the largest element from the heap, add its value to thescore, compute the new value asceil(value / 3), and push the new value back into the heap. - The
ceilvalue can be calculated in constant time.
- For each of the
- Completion:
- After completing
koperations, returnscore.
- After completing
Video explanation
Here is the video explaining this method in detail. Please check it out:
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n + k log n), wherenis the number of elements innums. Each of thekoperations involves extracting the maximum element and inserting a new element into the heap, both of which takeO(log n)time. - 🧺 Space complexity:
O(n), for storing elements in the heap.