A Binary String Game | Java program for the above approach ; Function to return the result of the game ; length of the string ; List to maintain the lengths of consecutive '1' s in the string ; Variable that keeps a track of the current length of the block of consecutive '1' s ; Adds non - zero lengths ; This takes care of the case when the last character is '1' ; Sorts the lengths in descending order ; Scores of the 2 players ; For player 1 ; For player 2 ; In case of a tie ; Print the result ; Driver Code ; Given string S ; Function Call
import java . io . * ; import java . util . * ; class GFG { public static String gameMax ( String S ) { int N = S . length ( ) ; List < Integer > list = new ArrayList < > ( ) ; int one = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( S . charAt ( i ) == '1' ) { one ++ ; } else { if ( one != 0 ) { list . add ( one ) ; } one = 0 ; } } if ( one != 0 ) { list . add ( one ) ; } Collections . sort ( list , Collections . reverseOrder ( ) ) ; int score_1 = 0 , score_2 = 0 ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) { if ( list . get ( i ) % 2 == 1 ) { score_1 += list . get ( i ) ; } else { score_2 += list . get ( i ) ; } } if ( score_1 == score_2 ) return " - 1" ; return ( score_1 > score_2 ) ? " Player ▁ 1" : " Player ▁ 2" ; } public static void main ( String [ ] args ) { String S = "11111101" ; System . out . println ( gameMax ( S ) ) ; } }