I first checked whether it is even possible to reach k — if there's any number in nums less than k, it's impossible, so I returned -1. Then, starting from the maximum element in nums, I processed all unique values in descending order. At each step, if the current value is greater than k and not all values above it are the same, it’s not a valid h, so I skip it. When I find a valid h, I count it as an operation and continue until we reach k.
class Solution:
def minOperations(self, nums: List[int], k: int) -> int:
if any(num < k for num in nums):
return -1
freq = Counter(nums)
unique_vals = sorted(freq.keys(), reverse=True)
operations = 0
above = []
for val in unique_vals:
if val <= k:
break
above.append(val)
if len(set(above)) == 1:
operations += 1
else:
operations += 1
above = [val]
return operations
- Time: O(n logn)
- Space: O(n)
