Minimum Operations to Make Array Values Equal to K - 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] = 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.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [2,1,2], k = 2
›
Output:
1
💡 Note:
Initially nums = [2,1,2]. Since 1 < 2, this should return -1. Let me fix: nums = [5,2,5,4], k = 2. Unique values: [5,4,2]. Need to reduce 5→4, then 4→2. Answer: 2 operations.
Example 2 — Already Equal
$
Input:
nums = [2,2,2], k = 2
›
Output:
0
💡 Note:
All elements already equal k=2, so no operations needed.
Example 3 — Impossible Case
$
Input:
nums = [1,2,3], k = 4
›
Output:
-1
💡 Note:
Some elements (1,2,3) are less than k=4, so impossible to achieve.
Constraints
- 1 ≤ nums.length ≤ 103
- 1 ≤ nums[i], k ≤ 103
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code