Minimum Operations to Make Array Values Equal to K Problem
Description
LeetCode Problem 3375.
You are given an integer array nums and an integer k.
An integer h is called valid if all values in the array that are strictly greater than h are identical.
For example, if nums = [10, 8, 10, 8], a valid integer is h = 9 because all nums[i] > 9 are equal to 10, but 5 is not a valid integer.
You are allowed to perform the following operation on nums:
- Select an integer
hthat is valid for the current values innums. - For each index
iwherenums[i] > h, setnums[i]toh.
Return the minimum number of operations required to make every element in nums equal to k. If it is impossible to make all elements equal to k, return -1.
Example 1:
Input: nums = [5,2,5,4,5], k = 2
Output: 2
Explanation:
The operations can be performed in order using valid integers 4 and then 2.
Example 2:
Input: nums = [2,1,2], k = 2
Output: -1
Explanation:
It is impossible to make all the values equal to 2.
Example 3:
Input: nums = [9,7,5,3], k = 1
Output: 4
Explanation:
The operations can be performed using valid integers in the order 7, 5, 3, and 1.
Constraints:
1 <= nums.length <= 1001 <= nums[i] <= 1001 <= k <= 100
Solution
Approach: Hash Table
Each operation can only lower values, so if some element is smaller than k the answer is -1.
Otherwise the best choice is to take h equal to the second largest distinct value: all values above it are the maximum, so they are identical and valid, and they all drop to h. Every operation therefore removes exactly one distinct value from the array. The distinct values greater than k each need one operation, and the value k itself needs none. So the answer is the number of distinct values, minus one if the minimum already equals k.
Scan the array, return -1 on any x < k, collect distinct values in a set and track the minimum mi; the answer is len(set) - (1 if mi == k else 0).
Complexity: time O(n), space O(n), where n is the length of nums.
from math import inf
class Solution:
def minOperations(self, nums: List[int], k: int) -> int:
s = set()
mi = inf
for x in nums:
if x < k:
return -1
mi = min(mi, x)
s.add(x)
return len(s) - int(k == mi)