Maximize β€œ10” Subsequences by replacing at most one 0 with 1


In this problem, we need to maximize the β€˜10’ subsequences in the given binary string by replacing the 0 or 1 β€˜0’ character with β€˜1’.

We can replace each β€˜0’ with β€˜1’ one after another and find a maximum number of β€˜10’ subsequences in the updated string.

Problem statement βˆ’ We have given a binary string named str1 containing only 0 and 1 characters. We can replace at most one β€˜0’ with β€˜1’ and need to find the maximum number of β€˜10’ subsequences in the given string.

Sample Examples

Input 

str1 = "10110"

Output 

4

Explanation

The β€˜10110’ substring contains only 3 β€˜10’ subsequences at {0, 1}, {2, 4}, and {3, 4} indexes.

When we update the β€˜0’ at first index by β€˜1’, we get the β€˜11110’ string containing the 4 β€˜10’ subsequences at {0, 4}, {1, 4}, {2, 4}, and {3, 4} indexes.

Input 

str1 = β€˜110’

Output 

2

Explanation

The string already contains the 2 β€˜10’ subsequences, so we don’t need to replace any β€˜0’ with β€˜1’.

Input 

str1 = "011010";

Output 

7

Explanation

The initial substring contains the 5 β€˜10’ subsequences at {1, 3}, {2, 3}, {1, 5}, {2, 5}, and {4, 5} indexes.

After replacing the β€˜0’ at the 0th index, we get 7 β€˜10’ subsequences at {0, 3}, {1, 3}, {2, 3}, {0, 5}, {1, 5}, {2, 5}, and {4, 5}.

If we replace the β€˜0’ at the 3rd index, we get 4 β€˜10’ subsequences.

If we replace the β€˜0’ at the 5th index, we get 2 β€˜10’ subsequences.

So, we have chosen the first β€˜0’, as it creates the maximum β€˜10’ subsequences in the given binary string.

Approach 1

When we change any β€˜0’ to β€˜1’, we get some new subsequences and lose some previously formed subsequences using the replaced β€˜0’.

When we replace the β€˜0’ with β€˜1’, the number of newly formed β€˜10’ subsequences is the same as the suffix zeros, and lost subsequences are a number of prefix zeros.

To solve the problem, we will prepare an array of prefix 1s and suffix zeros and take the maximum subtraction value of suffix 0’s and prefix 1’s, which are newly formed subsequences.

Algorithm

  • Step 1 βˆ’ Define the β€˜suffixZeros’ list to store the suffix zeros for each character of the binary string. Also, Initialize the last element of the list with 1 if the last character of the string is β€˜0’. Otherwise, initialize it with 0.

  • Step 2 βˆ’ Traverse the string in the reverse direction, and store the summation of suffix zeros for the previous element with 1 or 0 based on whether the current element is 0.

  • Step 3 βˆ’ Also, define the prefixOnes list to store the total number of prefix β€˜1’ at each string index. Also, initialize the first element of the list with 1 or 0 based on the first character of the string is 1.

  • Step 4 βˆ’ Start traversing the string, and store the summation of the prefix 1’s for the previous element and 1 or 0 based on whether the current element is 1 to the current prefix value.

  • Step 5 βˆ’ Next, we need to calculate the initial β€˜10’ subsequences in the given string.

  • Step 5.1 βˆ’ While traversing the string, if we get the β€˜1’, we need to add suffix zeros which are at the next index to the β€˜initialPairs’ variables, as β€˜1’ can form β€˜10’ subsequence with all next β€˜0’.

  • Step 6 βˆ’ Next, we need to calculate the total number of subsequences added after replacing the β€˜0’ with β€˜1’.

  • Step 6.1 βˆ’ Start traversing the string, and if the character at the pth index is β€˜0’, follow the below steps.

  • Step 6.2 βˆ’ If p is equal to the string length – 1, update the β€˜add’ variable with 0, as when we update the last β€˜0’, we can’t form new β€˜10’ subsequences.

  • Step 6.3 βˆ’ Else, update the β€˜add’ variable’s value with suffix zeros at the next index.

  • Step 6.4 βˆ’ If p is equal to 0, update the β€˜remove’ with 0, as when we replace the β€˜0’ at the first index with β€˜1’, it doesn’t affect other subsequences.

  • Step 6.5 βˆ’ Else, initialize the β€˜remove’ with prefix 1’s at the previous index.

  • Step 6.6 βˆ’ In the β€˜addPairs’ store, the subtraction of add and remove a value is the net added subsequences.

  • Step 6.7 βˆ’ Update the β€˜newPairs’ variable’s value with the β€˜addParis’ value if it is maximum.

  • Step 7 βˆ’ Return the sum of the initial pairs and added pairs.

Example

Following are the programs to the above approach βˆ’

#include <stdio.h>
#include <string.h>

int maxSubSeq(char str[]) {
   int str_len = strlen(str);
   // To store suffix zeros
   int suffixZeros[str_len + 1];
    
   // Checking if its value is 0
   suffixZeros[str_len - 1] = (str[str_len - 1] == '0') ? 1 : 0;
   for (int p = str_len - 2; p >= 0; p--) {
      suffixZeros[p] = suffixZeros[p + 1] + (str[p] == '0');
   }
    
   // To store prefix ones
   int prefixOnes[str_len];
    
   // Initializing prefixOnes[0]
   prefixOnes[0] = (str[0] == '1') ? 1 : 0;
    
   // Counting prefix ones
   for (int p = 1; p < str_len; p++) {
      prefixOnes[p] = prefixOnes[p - 1] + (str[p] == '1');
   }
   int initialPairs = 0;
   for (int p = 0; p < str_len; p++) {
      if (str[p] == '1')
        
      // Calculating initial pairs. '1' can form the subsequence '10' with all suffix zeros.
      initialPairs += suffixZeros[p + 1];
   }
    
   // New pairs
   int newPairs = 0;
   int add = 0, remove = 0;
    
   // Traverse the string
   for (int p = 0; p < str_len; p++) {
    
      // As we need to replace '0' and find the maximum subsequences
      if (str[p] == '0') {
         if (p == str_len - 1) {
            add = 0;
         } else {
            add = suffixZeros[p + 1];
         } 
         if (p == 0) {
            remove = 0;
         } else {
            remove = prefixOnes[p - 1];
         }
         // Total added pairs
         int addPairs = add - remove;
         // Finding the maximum new pairs
         if (addPairs > newPairs) {
            newPairs = addPairs;
         }
      }
   }
    
   // Maximum final pairs
   return initialPairs + newPairs;
}

int main() {
   char str1[] = "10110";
   printf("The maximum subsequences we can form by replacing the 0 with 1 is - %d\n", maxSubSeq(str1));
   return 0;
}

Output

The maximum subsequences we can form by replacing the 0 with 1 is - 4
#include <bits/stdc++.h>
using namespace std;

int maxSubSeq(string str) {
   int str_len = str.length();
   // To store suffix zeros
   vector<int> suffixZeros(str_len + 1);
   
   // Checking if its value is 0
   suffixZeros[str_len - 1] = str[str_len - 1] == '0';
   for (int p = str_len - 2; p >= 0; p--) {
      suffixZeros[p] = suffixZeros[p + 1] + (str[p] == '0');
   }
   
   // To store prefix ones
   vector<int> prefixOnes(str_len);
   
   // Initializing prefixOnes[0]
   prefixOnes[0] = (str[0] == '1');
   
   // Coutning prefix ones
   for (int p = 1; p < str_len; p++) {
      prefixOnes[p] = prefixOnes[p - 1] + (str[p] == '1');
   }
   int initialPairs = 0;
   for (int p = 0; p < str_len; p++) {
      if (str[p] == '1')
      
      // Calculating initial pairs. '1' can form the subsequence '10' with all suffix zeros.
      initialPairs += suffixZeros[p + 1];
   }
   
   // New pairs
   int newPairs = 0;
   int add = 0, remove = 0;
   
   // Traverse the string
   for (int p = 0; p < str_len; p++) {
   
      // As we need to replace '0' and find the maximum subsequences
      if (str[p] == '0') {
         if (p == str_len - 1) {
            add = 0;
         } else {
            add = suffixZeros[p + 1];
         } 
         if (p == 0) {
            remove = 0;
         } else {
            remove = prefixOnes[p - 1];
         }
         // Total added pairs
         int addPairs = add - remove;
         // Finding maximum new pairs
         newPairs = max(newPairs, addPairs);
      }
   }
   
   // Maximum final pairs
   return initialPairs + newPairs;
}
int main(){
   string str1 = "10110";
   cout << "The maximum subsequences we can form by replacing the 0 with 1 is - " << maxSubSeq(str1);
   return 0;
}

Output

The maximum subsequences we can form by replacing the 0 with 1 is - 4
public class MaxSubsequences {
   public static int maxSubSeq(String str) {
      int str_len = str.length();
      // To store suffix zeros
      int[] suffixZeros = new int[str_len + 1];

      // Checking if its value is 0
      suffixZeros[str_len - 1] = (str.charAt(str_len - 1) == '0') ? 1 : 0;
      for (int p = str_len - 2; p >= 0; p--) {
         suffixZeros[p] = suffixZeros[p + 1] + (str.charAt(p) == '0' ? 1 : 0);
      }

      // To store prefix ones
      int[] prefixOnes = new int[str_len];

      // Initializing prefixOnes[0]
      prefixOnes[0] = (str.charAt(0) == '1') ? 1 : 0;

      // Counting prefix ones
      for (int p = 1; p < str_len; p++) {
         prefixOnes[p] = prefixOnes[p - 1] + (str.charAt(p) == '1' ? 1 : 0);
      }
      int initialPairs = 0;
      for (int p = 0; p < str_len; p++) {
         if (str.charAt(p) == '1')

            // Calculating initial pairs. '1' can form the subsequence '10' with all suffix zeros.
            initialPairs += suffixZeros[p + 1];
      }

      // New pairs
      int newPairs = 0;
      int add = 0, remove = 0;

      // Traverse the string
      for (int p = 0; p < str_len; p++) {

         // As we need to replace '0' and find the maximum subsequences
         if (str.charAt(p) == '0') {
            if (p == str_len - 1) {
               add = 0;
            } else {
               add = suffixZeros[p + 1];
            }
            if (p == 0) {
               remove = 0;
            } else {
               remove = prefixOnes[p - 1];
            }
            // Total added pairs
            int addPairs = add - remove;
            // Finding maximum new pairs
            if (addPairs > newPairs) {
               newPairs = addPairs;
            }
         }
      }

      // Maximum final pairs
      return initialPairs + newPairs;
   }

   public static void main(String[] args) {
      String str1 = "10110";
      System.out.println("The maximum subsequences we can form by replacing the 0 with 1 is - " + maxSubSeq(str1));
   }
}

Output

The maximum subsequences we can form by replacing the 0 with 1 is - 4
def maxSubSeq(s):
   str_len = len(s)
   # To store suffix zeros
   suffix_zeros = [0] * (str_len + 1)

   # Checking if its value is 0
   suffix_zeros[str_len - 1] = 1 if s[str_len - 1] == '0' else 0
   for p in range(str_len - 2, -1, -1):
      suffix_zeros[p] = suffix_zeros[p + 1] + (s[p] == '0')

   # To store prefix ones
   prefix_ones = [0] * str_len

   # Initializing prefix_ones[0]
   prefix_ones[0] = 1 if s[0] == '1' else 0

   # Counting prefix ones
   for p in range(1, str_len):
      prefix_ones[p] = prefix_ones[p - 1] + (s[p] == '1')

   initial_pairs = 0
   for p in range(str_len):
      if s[p] == '1':
         # Calculating initial pairs. '1' can form the subsequence '10' with all suffix zeros.
         initial_pairs += suffix_zeros[p + 1]

   # New pairs
   new_pairs = 0
   add = 0
   remove = 0

   # Traverse the string
   for p in range(str_len):
      # As we need to replace '0' and find the maximum subsequences
      if s[p] == '0':
         if p == str_len - 1:
            add = 0
         else:
            add = suffix_zeros[p + 1]
         if p == 0:
            remove = 0
         else:
            remove = prefix_ones[p - 1]
         # Total added pairs
         add_pairs = add - remove
         # Finding the maximum new pairs
         new_pairs = max(new_pairs, add_pairs)

   # Maximum final pairs
   return initial_pairs + new_pairs

str1 = "10110"
print("The maximum subsequences we can form by replacing the 0 with 1 is -", maxSubSeq(str1))

Output

The maximum subsequences we can form by replacing the 0 with 1 is - 4

Time complexity – O(N) to calculate suffix zeros, prefix 1s, and find maximum β€˜10’ subsequences by replacing at most β€˜0’ with β€˜1’.

Space complexity – O(N) to store the prefix 1’s and suffix 0’s.

By solving the above problem, programmers learned to find the prefix and suffix arrays. Also, we learned to get the output by hit and trial case, as we replace each β€˜0’ with β€˜1’ and find the maximum β€˜10’ subsequences in the given string.

Updated on: 23-Oct-2023

44 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements