[LeetCode] Minimum Operations to Make Array Values Equal to K

3375. Minimum Operations to Make Array Values Equal to K

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 h that is valid for the current values in nums.
  • For each index i where nums[i] > h, set nums[i] to h.

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int minOperations(vector<int>& nums, int k) {
sort(begin(nums), end(nums));
if (nums[0] < k) return -1;
int res = 0;
while(nums.size() and nums.back() > k) {
int x = nums.back();
res++;
while(nums.size() and nums.back() == x) nums.pop_back();
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/12/08/PS/LeetCode/minimum-operations-to-make-array-values-equal-to-k/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.