Skip to content

3375. Minimum Operations to Make Array Values Equal to K 👎

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
 public:
  int minOperations(vector<int>& nums, int k) {
    const unordered_set<int> numsSet{nums.begin(), nums.end()};
    const int mn = ranges::min(nums);
    if (mn < k)
      return -1;
    if (mn > k)
      return numsSet.size();
    return numsSet.size() - 1;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
  public int minOperations(int[] nums, int k) {
    Set<Integer> numsSet = Arrays.stream(nums).boxed().collect(Collectors.toSet());
    final int mn = Arrays.stream(nums).min().getAsInt();
    if (mn < k)
      return -1;
    if (mn > k)
      return numsSet.size();
    return numsSet.size() - 1;
  }
}
1
2
3
4
5
6
7
8
9
class Solution:
  def minOperations(self, nums: list[int], k: int) -> int:
    numsSet = set(nums)
    mn = min(nums)
    if mn < k:
      return -1
    if mn > k:
      return len(numsSet)
    return len(numsSet) - 1