Minimize operations to make given binary string as all 1s by repeatedly converting K consecutive characters to 1
Last Updated :
20 Dec, 2021
Given a binary string str of N characters an integer K, the task is to find the minimum moves required to convert all characters of the string to 1’s where at each move, K consecutive characters can be converted to 1.
Example:
Input: str=”0010″, K=3
Output: 2
Explanation:
Move 1: Select the substring from 0 to 2 and replace it with all 1.
Move 2: Select the substring from 1 to 3 and replace it with all 1.
Input: str=”0000010″, K=1
Output: 6
Approach: This problem can be solved using a greedy approach. To solve this problem, follow the below steps:
- Create a variable cnt, to store the minimum number of moves required. Initialize it with 0.
- Traverse the string using a variable i and str[i] = ‘0’, then update i to i + K and increase cnt by 1, because no matter what these characters are, a move is always required to convert the character str[i] to ‘1’.
- After the loop ends, return cnt which will be the required answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minMoves(string str, int K)
{
int N = str.size();
int cnt = 0;
int i = 0;
while (i < N) {
if (str[i] == '0' ) {
i += K;
cnt += 1;
}
else {
i++;
}
}
return cnt;
}
int main()
{
string str = "0010" ;
int K = 3;
cout << minMoves(str, K);
}
|
Java
class GFG {
static int minMoves(String str, int K) {
int N = str.length();
int cnt = 0 ;
int i = 0 ;
while (i < N) {
if (str.charAt(i) == '0' ) {
i += K;
cnt += 1 ;
}
else {
i++;
}
}
return cnt;
}
public static void main(String args[]) {
String str = "0010" ;
int K = 3 ;
System.out.println(minMoves(str, K));
}
}
|
Python3
def minMoves( str , K):
N = len ( str )
cnt = 0
i = 0
while (i < N):
if ( str [i] = = '0' ):
i + = K
cnt + = 1
else :
i + = 1
return cnt
str = "0010"
K = 3
print (minMoves( str , K))
|
C#
using System;
class GFG
{
static int minMoves( string str, int K)
{
int N = str.Length;
int cnt = 0;
int i = 0;
while (i < N) {
if (str[i] == '0' ) {
i += K;
cnt += 1;
}
else {
i++;
}
}
return cnt;
}
public static void Main()
{
string str = "0010" ;
int K = 3;
Console.Write(minMoves(str, K));
}
}
|
Javascript
<script>
function minMoves(str, K) {
let N = str.length;
let cnt = 0;
let i = 0;
while (i < N) {
if (str[i] == '0' ) {
i += K;
cnt += 1;
}
else {
i++;
}
}
return cnt;
}
let str = "0010" ;
let K = 3;
document.write(minMoves(str, K));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...