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.

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.

Example 1
Inputnums = [5,2,5,4,5], k = 2
Output2
The operations can be performed in order using valid integers 4 and then 2.
Example 2
Inputnums = [2,1,2], k = 2
Output-1
It is impossible to make all the values equal to 2.

Constraints

  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 100
  • 1 <= k <= 100

Asked at 4 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate