3375. Minimum Operations to Make Array Values Equal to K
MediumView on LeetCode
Time: O(n)
Space: O(n)
Problem Overview
Minimum operations to make array values equal to k.
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;
}
}Was this solution helpful?
Related Problems
- 4. Median of Two Sorted Arrays(Hard)
- 11. Container With Most Water(Medium)
- 15. 3Sum(Medium)
- 16. 3Sum Closest(Medium)
- 26. Remove Duplicates from Sorted Array(Easy)
- 27. Remove Element(Easy)