Maximum Balanced String Partitions | C ++ program to find a maximum number X , such that a given string can be partitioned into X substrings that are each balanced ; Function to find a maximum number X , such that a given string can be partitioned into X substrings that are each balanced ; If the size of the string is 0 , then answer is zero ; variable that represents the number of ' R ' s and ' L ' s ; To store maximum number of possible partitions ; increment the variable r if the character in the string is ' R ' ; increment the variable l if the character in the string is ' L ' ; if r and l are equal , then increment ans ; Return the required answer ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int BalancedPartition ( string str , int n ) { if ( n == 0 ) return 0 ; int r = 0 , l = 0 ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == ' R ' ) { r ++ ; } else if ( str [ i ] = ' L ' ) { l ++ ; } if ( r == l ) { ans ++ ; } } return ans ; } int main ( ) { string str = " LLRRRLLRRL " ; int n = str . size ( ) ; cout << BalancedPartition ( str , n ) << endl ; return 0 ; }