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 innums
that are strictly greater thanh
are equal. - For each index
i
wherenums[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 <= 100
1 <= nums[i], k <= 100
- Check for impossibility: If any element in
nums
is 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