Longest subsequence of the form 0 * 1 * 0 * in a binary string | CPP program to find longest subsequence of the form 0 * 1 * 0 * in a binary string ; Returns length of the longest subsequence of the form 0 * 1 * 0 * ; Precomputing values in three arrays pre_count_0 [ i ] is going to store count of 0 s in prefix str [ 0. . i - 1 ] pre_count_1 [ i ] is going to store count of 1 s in prefix str [ 0. . i - 1 ] post_count_0 [ i ] is going to store count of 0 s in suffix str [ i - 1. . n - 1 ] ; string is made up of all 0 s or all 1 s ; Compute result using precomputed values ; driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int longestSubseq ( string s ) { int n = s . length ( ) ; int pre_count_0 [ n + 2 ] ; int pre_count_1 [ n + 1 ] ; int post_count_0 [ n + 1 ] ; pre_count_0 [ 0 ] = 0 ; post_count_0 [ n + 1 ] = 0 ; pre_count_1 [ 0 ] = 0 ; for ( int j = 1 ; j <= n ; j ++ ) { pre_count_0 [ j ] = pre_count_0 [ j - 1 ] ; pre_count_1 [ j ] = pre_count_1 [ j - 1 ] ; post_count_0 [ n - j + 1 ] = post_count_0 [ n - j + 2 ] ; if ( s [ j - 1 ] == '0' ) pre_count_0 [ j ] ++ ; else pre_count_1 [ j ] ++ ; if ( s [ n - j ] == '0' ) post_count_0 [ n - j + 1 ] ++ ; } if ( pre_count_0 [ n ] == n pre_count_0 [ n ] == 0 ) return n ; int ans = 0 ; for ( int i = 1 ; i <= n ; i ++ ) for ( int j = i ; j <= n ; j ++ ) ans = max ( pre_count_0 [ i - 1 ] + pre_count_1 [ j ] - pre_count_1 [ i - 1 ] + post_count_0 [ j + 1 ] , ans ) ; return ans ; } int main ( ) { string s = "000011100000" ; cout << longestSubseq ( s ) ; return 0 ; }