3192. Minimum Operations to Make Binary Array Elements Equal to One II
EasyView on LeetCode
Time: O(n)
Space: O(1)
Advertisement
Intuition
Minimum operations to alternate binary array. Compare with patterns 010101... and 101010..., return min mismatches.
Algorithm
- 1Count mismatches with pattern starting with 0. Answer = min(mismatches, n - mismatches).
Common Pitfalls
- •Two valid alternating patterns. Count mismatches with one, n-count for the other. Return min.
3192.cs
C#
// Approach: Greedy; count flips needed tracking current parity.
// Time: O(n) Space: O(1)
public class Solution {
public int MinOperations(int[] nums) {
int n = nums.Length, ans = 0, times = 0;
for(int i = 0; i < n; i++)
{
if((nums[i] == 1 && times % 2 == 1) || (nums[i] == 0 && times % 2 == 0))
times++;
}
return times;
}
}Advertisement
Was this solution helpful?