Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created April 9, 2025 17:25
Show Gist options
  • Save Ifihan/a8e51adab53b9fa61d0290434ad7069b to your computer and use it in GitHub Desktop.
Save Ifihan/a8e51adab53b9fa61d0290434ad7069b to your computer and use it in GitHub Desktop.
Minimum Operations to Make Array Values Equal to K

Question

Approach

I first checked whether it is even possible to reach k — if there's any number in nums less than k, it's impossible, so I returned -1. Then, starting from the maximum element in nums, I processed all unique values in descending order. At each step, if the current value is greater than k and not all values above it are the same, it’s not a valid h, so I skip it. When I find a valid h, I count it as an operation and continue until we reach k.

Implementation

class Solution:
    def minOperations(self, nums: List[int], k: int) -> int:
        if any(num < k for num in nums):
            return -1
        
        freq = Counter(nums)
        unique_vals = sorted(freq.keys(), reverse=True)
        operations = 0
        above = []

        for val in unique_vals:
            if val <= k:
                break
            above.append(val)
            if len(set(above)) == 1:
                operations += 1
            else:
                operations += 1
                above = [val]

        return operations

Complexities

  • Time: O(n logn)
  • Space: O(n)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment