Maximum flips possible such that no pair of adjacent elements are both 1
Given a binary array arr[] of size N, the task is to find the maximum count of 0s that can be converted into 1s such that no pair of adjacent array elements are 1.
Examples:
Input: arr[] = { 1, 0, 0, 0, 1 }
Output: 1
Explanation:
Updating arr[2] to 1 modifies arr[] to { 1, 0, 1, 0, 1 }
Therefore, the required output is 1
Input: arr[] = { 0, 0, 1, 0, 0, 0, 0, 1, 0, 0 }
Output: 3
Explanation:
Updating arr[0], arr[5] and arr[9] modifies arr[] to { 1, 0, 1, 0, 0, 1, 0, 1, 0, 1 }
Therefore, the required output is 3
Approach: The problem can be solved using Greedy technique. Follow the steps below to solve the problem:
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void maxPositionsOccupied(vector< int >& arr)
{
if (arr.size() == 0) {
cout << 0;
return ;
}
arr.push_back(0);
arr.insert(arr.begin(), 0);
int ans = 0;
int i = 0;
while ((i < arr.size() - 2)) {
if ((arr[i] == 0) && (arr[i + 1] == 0)
&& (arr[i + 2] == 0)) {
ans++;
arr[i + 1] = 1;
}
i++;
}
cout << ans;
}
int main()
{
vector< int > arr = { 1, 0, 0, 0, 1 };
maxPositionsOccupied(arr);
return 0;
}
|
Java
public class GFG
{
static void maxPositionsOccupied( int [] arr)
{
if (arr.length == 0 )
{
System.out.print( 0 );
return ;
}
int ans = 0 ;
int i = 0 ;
while ((i < arr.length - 2 ))
{
if ((arr[i] == 0 ) &&
(arr[i + 1 ] == 0 ) &&
(arr[i + 2 ] == 0 ))
{
ans++;
arr[i + 1 ] = 1 ;
}
i++;
}
System.out.print(ans);
}
public static void main(String[] args)
{
int [] arr = { 1 , 0 , 0 , 0 , 1 };
maxPositionsOccupied(arr);
}
}
|
Python3
def maxPositionsOccupied(arr):
if ( len (arr) = = 0 ):
print ( 0 )
arr.append( 0 )
arr.insert( 0 , 0 )
ans = 0
i = 0
while ((i < len (arr) - 2 )):
if ((arr[i] = = 0 ) and
(arr[i + 1 ] = = 0 ) and
(arr[i + 2 ] = = 0 )):
ans + = 1
arr[i + 1 ] = 1
i + = 1
print (ans)
if __name__ = = '__main__' :
arr = [ 1 , 0 , 0 , 0 , 1 ]
maxPositionsOccupied(arr)
|
C#
using System;
class GFG{
static void maxPositionsOccupied( int [] arr)
{
if (arr.Length == 0)
{
Console.Write(0);
return ;
}
int ans = 0;
int i = 0;
while ((i < arr.Length - 2))
{
if ((arr[i] == 0) &&
(arr[i + 1] == 0) &&
(arr[i + 2] == 0))
{
ans++;
arr[i + 1] = 1;
}
i++;
}
Console.Write(ans);
}
static void Main()
{
int [] arr = { 1, 0, 0, 0, 1 };
maxPositionsOccupied(arr);
}
}
|
Javascript
<script>
function maxPositionsOccupied(arr)
{
if (arr.length == 0)
{
document.write(0);
return ;
}
let ans = 0;
let i = 0;
while ((i < arr.length - 2))
{
if ((arr[i] == 0) &&
(arr[i + 1] == 0) &&
(arr[i + 2] == 0))
{
ans++;
arr[i + 1] = 1;
}
i++;
}
document.write(ans);
}
let arr = [ 1, 0, 0, 0, 1 ];
maxPositionsOccupied(arr);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Last Updated :
12 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...