Problem
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:
| |
Example 2:
| |
Example 3:
| |
Constraints:
1 <= nums.length <= 1001 <= nums[i] <= 1001 <= k <= 100
Examples
Solution
Method 1 - Using Set
The problem involves transforming an array so all elements equal the target k. Here’s the merged explanation:
- Early Feasibility Check: If
kis greater than the smallest number in the array, transforming the array intokis impossible. We return-1immediately to avoid further computations. - Unique Elements Count: Each unique number in the array corresponds to a potential operation required to transform values into
k. Using a set, we count unique values in the array. - Optimised Operations: If
kis among these unique values, one operation is saved because no transformation is needed fork. Otherwise, the total required operations will match the count of unique values.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n). For finding the minimum value and creating a set of unique elements. - 🧺 Space complexity:
O(n)in the worst case, all the elements in array can be unique.