text: Concatenate strings in any order to get Maximum Number of " AB " | C # implementation of above approach ; Function to find maximum number of ABs ; variable A , B , AB for count strings that end with ' A ' but not end with ' B ' , ' B ' but does not end with ' A ' and ' B ' and ends with ' A ' respectively . ; ' AB ' is already present in string before concatenate them ; count of strings that begins with ' B ' and ends with 'A ; count of strings that begins with ' B ' but does not end with ' A ' ; count of strings that ends with ' A ' but not end with ' B ' ; updating the value of ans and add extra count of ' AB ' ; Driver Code
code: using System ; class GFG { static int maxCountAB ( string [ ] s , int n ) { int A = 0 , B = 0 , BA = 0 , ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { string S = s [ i ] ; int L = S . Length ; for ( int j = 0 ; j < L - 1 ; j ++ ) { if ( S [ j ] == ' A ' && S [ j + 1 ] == ' B ' ) { ans ++ ; } } if ( S [ 0 ] == ' B ' && S [ L - 1 ] == ' A ' ) BA ++ ; else if ( S [ 0 ] == ' B ' ) B ++ ; else if ( S [ L - 1 ] == ' A ' ) A ++ ; } if ( BA == 0 ) ans += Math . Min ( B , A ) ; else if ( A + B == 0 ) ans += BA - 1 ; else ans += BA + Math . Min ( B , A ) ; return ans ; } public static void Main ( ) { string [ ] s = { " ABCA " , " BOOK " , " BAND " } ; int n = s . Length ; Console . WriteLine ( maxCountAB ( s , n ) ) ; } }