Problem Statement:
You are given a binary array, you need to choose any 3 consecutive elements and you need to flip al the 3 elements.
By making the above operations, you need to return the minimum number of operations to make all the elements to 1.
Example:
Input: arr = [1, 1, 0, 0, 0]
Output: 1
change last 3 elements to 1.
Solution:
Solution is very simple.
We need to flip 3 consecutive numbers when we encounter 0, and to flip we need to use XOR.
Then check at the end of the array check if you are seeing any 0, if yes, return -1, else return the count.
Code Solution
#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
using namespace std;
int solution(vector<int>& nums)
{
int n = nums.size();
int res = 0;
for (int i = 0; i <= n - 3; i++)
{
if (nums[i] == 0)
{
nums[i] ^= 1;
nums[i + 1] ^= 1;
nums[i + 2] ^= 1;
res++;
}
}
for (int num : nums)
{
if (num == 0)
return -1;
}
return res;
}
int main()
{
vector<int> arr = {1, 1, 0, 0, 0};
cout<<solution(arr);
return 0;
}
Output
1