Problem of The Day: Minimum Operations to Exceed Threshold Value II
Problem Statement
Intuition
The problem requires minimizing operations to ensure all elements in the list nums
are at least k
. The key observation is that we can iteratively combine the two smallest numbers to form a larger number, leveraging a min-heap for efficiency.
Approach
- Use a Min-Heap: Convert the list
nums
into a min-heap usingheapq.heapify(nums)
, allowing us to efficiently extract the smallest two elements. - Iterate Until Condition is Met: While there are at least two elements in
nums
:- Extract the two smallest elements
x
andy
. - If both
x
andy
are greater than or equal tok
, return the operation count. - Otherwise, combine them using the formula
min(x, y) * 2 + max(x, y)
, and push the result back into the heap. - Increment the operation counter.
- Extract the two smallest elements
- Return the Operation Count: If we exhaust the heap before all elements reach
k
, return the count of operations performed.
Complexity
-
Time Complexity:
- Heap operations (
heapify
,heappop
, andheappush
) takeO(log n)
, and we perform these up toO(n)
times. - Overall complexity: O(n log n).
- Heap operations (
-
Space Complexity:
- The heap is stored in place, so the space complexity is O(1) (excluding input storage).
Code
import heapq
from typing import List
class Solution:
def minOperations(self, nums: List[int], k: int) -> int:
heapq.heapify(nums)
ops = 0
while len(nums) >= 2:
x = heapq.heappop(nums)
y = heapq.heappop(nums)
if x >= k and y >= k:
return ops
heapq.heappush(nums, min(x, y) * 2 + max(x, y))
ops += 1
return ops
Editorial
Approach: Priority Queue
class Solution:
def minOperations(self, nums: List[int], k: int) -> int:
heapq.heapify(nums)
num_operations = 0
while nums[0] < k:
x = heapq.heappop(nums)
y = heapq.heappop(nums)
heapq.heappush(nums, min(x, y) * 2 + max(x, y))
num_operations += 1
return num_operations
- time: O(nlogn)
- space: O(n)