[LeetCode] Minimum Operations to Make Binary Array Elements Equal to One I

3191. Minimum Operations to Make Binary Array Elements Equal to One I

You are given a binary array nums.

You can do the following operation on the array any number of times (possibly zero):

  • Choose any 3 consecutive elements from the array and flip all of them.

Flipping an element means changing its value from 0 to 1, and from 1 to 0.

Return the minimum number of operations required to make all elements in nums equal to 1. If it is impossible, return -1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int minOperations(vector<int>& A) {
int n = A.size(), res = 0;
for(int i = 0; i < n - 2; i++) {
if(A[i]) continue;
A[i] = !A[i];
A[i+1] = !A[i+1];
A[i+2] = !A[i+2];
res++;
}
if(A[n-1] == 0 or A[n-2] == 0) return -1;
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/06/23/PS/LeetCode/minimum-operations-to-make-binary-array-elements-equal-to-one-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.