3375. Minimum Operations to Make Array Values Equal to K
Description
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 innums
. - For each index
i
wherenums[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 <= 100
1 <= nums[i] <= 100
1 <= k <= 100
Solutions
Solution 1: Hash Table
According to the problem description, we can choose the second largest value in the current array as the valid integer \(h\) each time, and change all numbers greater than \(h\) to \(h\). This minimizes the number of operations. Additionally, since the operation reduces the numbers, if there are numbers in the current array smaller than \(k\), we cannot make all numbers equal to \(k\), so we directly return -1.
We iterate through the array \(\textit{nums}\). For the current number \(x\), if \(x < k\), we directly return -1. Otherwise, we add \(x\) to the hash table and update the minimum value \(\textit{mi}\) in the current array. Finally, we return the size of the hash table minus 1 (if \(\textit{mi} = k\), we need to subtract 1).
Time complexity is \(O(n)\), and space complexity is \(O(n)\), where \(n\) is the length of the array \(\textit{nums}\).
1 2 3 4 5 6 7 8 9 10 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
1 2 3 4 5 6 7 8 |
|
1 2 3 4 5 6 7 8 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|