~/leetcode$cat3375. Minimum-Operations-To-Make-Array-Values-Equal-To-K
One of the most confusing descriptions I’ve seen in a while. After reading the question very very very carefully, we can see that there are only 3 cases to consider when comparing the smallest element in nums and k:
- If the smallest element in
numsis smaller thank, it is not possible to make all values in the array equal tokas there are no operations that increase the value of elements in the array. Therefore, in this case, we return-1 - If the smallest element in
numsis greater thank, we would need to use 1 operation for each unique element in the list. Therefore, we would need to uselen(unique)operations whereuniqueis a list/set of unique elements innums - If the smallest element in
numsis equal tok, we have a similar case to case 2, except we don’t need to use an operation at the end (sincekis equal to the smallest element innums). Therefore, we would need to uselen(unique) - 1operations whereuniqueis a list/set of unique elements innums
class Solution(object):
def minOperations(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
unique = set(nums)
smallest = float('inf')
for num in unique:
smallest = min(smallest, num)
if smallest < k:
return -1
if smallest > k:
return len(unique)
return len(unique) - 1
Time Complexity:
O(n)Space Complexity:
O(n)Time Taken:
7m 45s