Given a string consisting only of 1’s and 0’s. In one flip we can change any continuous sequence of this string. Find this minimum number of flips so the string consist of same characters only.
Examples:
Input : 00011110001110
Output : 2
We need to convert 1's sequence
so string consist of all 0's.
Input : 010101100011
Output : 4
We need to find the min flips in string so all characters are equal. All we have to find numbers of sequence which consisting of 0’s or 1’s only. Then number of flips required will be half of this number as we can change all 0’s or all 1’s.
C++
#include <bits/stdc++.h>
using namespace std;
int findFlips( char str[], int n)
{
char last = ' ' ; int res = 0;
for ( int i = 0; i < n; i++) {
if (last != str[i])
res++;
last = str[i];
}
return res / 2;
}
int main()
{
char str[] = "00011110001110" ;
int n = strlen (str);
cout << findFlips(str, n);
return 0;
}
|
Java
public class minFlips {
static int findFlips(String str, int n)
{
char last = ' ' ; int res = 0 ;
for ( int i = 0 ; i < n; i++) {
if (last != str.charAt(i))
res++;
last = str.charAt(i);
}
return res / 2 ;
}
public static void main(String[] args)
{
String str = "00011110001110" ;
int n = str.length();
System.out.println(findFlips(str, n));
}
}
|
Python 3
def findFlips( str , n):
last = ' '
res = 0
for i in range ( n) :
if (last ! = str [i]):
res + = 1
last = str [i]
return res / / 2
if __name__ = = "__main__" :
str = "00011110001110"
n = len ( str )
print (findFlips( str , n))
|
C#
using System;
public class GFG {
static int findFlips(String str, int n)
{
char last = ' ' ; int res = 0;
for ( int i = 0; i < n; i++) {
if (last != str[i])
res++;
last = str[i];
}
return res / 2;
}
public static void Main()
{
String str = "00011110001110" ;
int n = str.Length;
Console.Write(findFlips(str, n));
}
}
|
PHP
<?php
function findFlips( $str , $n )
{
$last = ' ' ;
$res = 0;
for ( $i = 0; $i < $n ; $i ++)
{
if ( $last != $str [ $i ])
$res ++;
$last = $str [ $i ];
}
return intval ( $res / 2);
}
$str = "00011110001110" ;
$n = strlen ( $str );
echo findFlips( $str , $n );
?>
|
Javascript
<script>
function findFlips( str , n) {
var last = ' ' ;
var res = 0;
for (i = 0; i < n; i++) {
if (last != str.charAt(i))
res++;
last = str.charAt(i);
}
return parseInt(res / 2);
}
var str = "00011110001110" ;
var n = str.length;
document.write(findFlips(str, n));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Output:
2
This article is contributed by nuclode. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.