You are given an integer array nums and an integer k.
You can perform the following operation:
- Choose an integer
h(called valid) such that all elements innumsthat are strictly greater thanhare equal. - For each index
iwherenums[i] > h, setnums[i] = h.
Your goal is to make all values in nums equal to k using the minimum number of operations.
Return the minimum number of operations, or -1 if it's impossible.
An integer h is valid if all values in nums that are strictly greater than h are equal.
-
Operation 1: Choose h = 4 β nums becomes [4, 2, 4, 4, 4]
-
Operation 2: Choose h = 2 β nums becomes [2, 2, 2, 2, 2]
There's an element (1) smaller than k, so it's impossible.
-
h = 7 β [7, 7, 5, 3]
-
h = 5 β [5, 5, 5, 3]
-
h = 3 β [3, 3, 3, 3]
-
h = 1 β [1, 1, 1, 1]
1 <= nums.length <= 1001 <= nums[i], k <= 100
- Check for impossibility: If any element in
numsis less thank, return-1(since we can only decrease values). - Sort unique values in descending order.
- Count valid operations from top down to
k.
class Solution:
def minOperations(self, nums, k):
if any(num < k for num in nums):
return -1
from collections import Counter
freq = Counter(nums)
unique_values = sorted(freq.keys(), reverse=True)
operations = 0
i = 0
while i < len(unique_values) and unique_values[i] > k:
operations += 1
i += 1
return operations