Given a binary array arr, the task is to find the maximum number of 0s that can be flipped such that the array has no adjacent 1s, i.e. the array does not contain any two 1s at consecutive indices.
Examples:
Input: arr[] = {1, 0, 0, 0, 1}
Output: 1
Explanation:
The 0 at index 2 can be replaced by 1.
Input: arr[] = {1, 0, 0, 1}
Output: 0
Explanation:
No 0 (zeroes) can be replaced by 1 such that no two consecutive indices have 1.
Approach:
- Iterate over the array and for every index which have 0, check if its adjacent two indices have 0 or not. For the last and first index of the array, check for the adjacent left and right index respectively.
- For every such index satisfying the above condition, increase the count.
- Print the final count at the end as the required answer
Below is the implementation of the above approach:
C++
#include<bits/stdc++.h>
using namespace std;
int canReplace( int array[], int n)
{
int i = 0, count = 0;
while (i < n)
{
if (array[i] == 0 &&
(i == 0 || array[i - 1] == 0) &&
(i == n - 1|| array[i + 1] == 0))
{
array[i] = 1;
count++;
}
i++;
}
return count;
}
int main()
{
int array[5] = { 1, 0, 0, 0, 1 };
cout << canReplace(array, 5);
}
|
Java
public class geeks {
public static int canReplace(
int [] array)
{
int i = 0 , count = 0 ;
while (i < array.length) {
if (array[i] == 0
&& (i == 0
|| array[i - 1 ] == 0 )
&& (i == array.length - 1
|| array[i + 1 ] == 0 )) {
array[i] = 1 ;
count++;
}
i++;
}
return count;
}
public static void main(String[] args)
{
int [] array = { 1 , 0 , 0 , 0 , 1 };
System.out.println(canReplace(array));
}
}
|
Python3
def canReplace(arr, n):
i = 0
count = 0
while (i < n):
if (arr[i] = = 0 and
(i = = 0 or arr[i - 1 ] = = 0 ) and
(i = = n - 1 or arr[i + 1 ] = = 0 )):
arr[i] = 1
count + = 1
i + = 1
return count
if __name__ = = '__main__' :
arr = [ 1 , 0 , 0 , 0 , 1 ]
print (canReplace(arr, 5 ))
|
C#
using System;
class GFG{
public static int canReplace( int [] array)
{
int i = 0, count = 0;
while (i < array.Length)
{
if (array[i] == 0 &&
(i == 0 || array[i - 1] == 0) &&
(i == array.Length - 1 || array[i + 1] == 0))
{
array[i] = 1;
count++;
}
i++;
}
return count;
}
public static void Main(String []args)
{
int [] array = { 1, 0, 0, 0, 1 };
Console.WriteLine(canReplace(array));
}
}
|
Javascript
<script>
function canReplace(array, n)
{
var i = 0, count = 0;
while (i < n)
{
if (array[i] == 0 &&
(i == 0 || array[i - 1] == 0) &&
(i == n - 1|| array[i + 1] == 0))
{
array[i] = 1;
count++;
}
i++;
}
return count;
}
array = [1, 0, 0, 0, 1]
document.write(canReplace(array, 5));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
07 Dec, 2022
Like Article
Save Article