3192. Minimum Operations to Make Binary Array Elements Equal to One II
EasyView on LeetCode
Time: O(n)
Space: O(1)
Problem Overview
Minimum operations to alternate binary array.
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;
}
}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)
- 22. Generate Parentheses(Medium)
- 26. Remove Duplicates from Sorted Array(Easy)