#2530
Maximal Score After Applying K Operations
MediumArrayGreedyHeap (Priority Queue)HeapGreedy
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(k log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(k log n)Space O(n)
In the optimal approach, we utilize a max-heap (priority queue) to efficiently get the maximum element in O(log n) time. This allows us to perform k operations in a much faster manner, significantly reducing the overall time complexity.
⚙️
Algorithm
3 steps- 1Step 1: Create a max-heap from the nums array.
- 2Step 2: Initialize score to 0.
- 3Step 3: For k iterations, extract the maximum element from the heap, add it to the score, and push back its updated value (ceil(max_element / 3)).
solution.py11 lines
1import heapq
2
3def maxScore(nums, k):
4 max_heap = [-num for num in nums] # Invert values for max-heap
5 heapq.heapify(max_heap)
6 score = 0
7 for _ in range(k):
8 max_val = -heapq.heappop(max_heap)
9 score += max_val
10 heapq.heappush(max_heap, -(-max_val // 3)) # ceil division
11 return scoreℹ
Complexity note: The time complexity is O(k log n) because each of the k operations involves extracting the maximum from the heap and then inserting the updated value back, both of which take O(log n) time. The space complexity is O(n) due to the storage of the heap.
- 1Always choose the maximum element to maximize the score.
- 2Using a heap allows efficient retrieval and updating of the maximum element.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.