3375. Minimum Operations to Make Array Values Equal to K
MediumView on LeetCode
Time: O(n)
Space: O(n)
Advertisement
Intuition
Minimum operations to make array values equal to k. All elements must be reducible to k.
Algorithm
- 1If any element < k: return -1. Count distinct values > k (each needs one operation).
Common Pitfalls
- •Can only decrease values. If element < k: impossible. Each distinct value > k needs one op.
3375.cs
C#
// Approach: Collect unique values > k; if any < k return -1; else count distinct unique values > k.
// Time: O(n) Space: O(n)
public class Solution
{
public int MinOperations(int[] nums, int k)
{
HashSet<int> numsSet = new HashSet<int>(nums);
int mn = nums.Min();
if (mn < k)
return -1;
if (mn > k)
return numsSet.Count;
return numsSet.Count - 1;
}
}Advertisement
Was this solution helpful?