Concatenate strings in any order to get Maximum Number of " AB " | 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
function maxCountAB ( s , n ) { var A = 0 , B = 0 , BA = 0 , ans = 0 ; for ( var i = 0 ; i < n ; i ++ ) { var S = s [ i ] ; var L = S . length ; for ( var j = 0 ; j < L - 1 ; j ++ ) { if ( S [ j ] == ' ' && S [ j + 1 ] == ' ' ) { ans ++ ; } } if ( S [ 0 ] == ' ' && S [ L - 1 ] == ' ' ) BA ++ ; else if ( S [ 0 ] == ' ' ) B ++ ; else if ( S [ L - 1 ] == ' ' ) 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 ; } var s = [ " " , " " , " " ] ; var n = s . length ; document . write ( maxCountAB ( s , n ) ) ;