A Binary String Game | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; string gameMax ( string S ) { int N = S . length ( ) ; vector < int > list ; int one = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( S [ i ] == '1' ) { one ++ ; } else { if ( one != 0 ) { list . push_back ( one ) ; } one = 0 ; } } if ( one != 0 ) { list . push_back ( one ) ; } sort ( list . begin ( ) , list . end ( ) , greater < int > ( ) ) ; int score_1 = 0 , score_2 = 0 ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) { if ( list [ i ] % 2 == 1 ) { score_1 += list [ i ] ; } else { score_2 += list [ i ] ; } } if ( score_1 == score_2 ) return " - 1" ; return ( score_1 > score_2 ) ? " Player ▁ 1" : " Player ▁ 2" ; } int main ( ) { string S = "11111101" ; cout << gameMax ( S ) ; }