Maximum Balanced String Partitions | Java 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
import java . util . * ; class GFG { static 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 . charAt ( i ) == ' R ' ) { r ++ ; } else if ( str . charAt ( i ) == ' L ' ) { l ++ ; } if ( r == l ) { ans ++ ; } } return ans ; } public static void main ( String [ ] args ) { String str = " LLRRRLLRRL " ; int n = str . length ( ) ; System . out . print ( BalancedPartition ( str , n ) + "NEW_LINE"); } }