Determine the winner of a game of deleting Characters from a String | C ++ program for the above approach ; Function to find the winner of the game when both players play optimally ; Stores the frequency of all digit ; Stores the scores of player1 and player2 respectively ; Iterate to store frequencies ; Turn for the player1 ; Add score of player1 ; Add score of player2 ; Check if its a draw ; If score of player 1 is greater ; Otherwise ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void determineWinner ( string str ) { vector < int > A ( 10 ) ; int sum1 = 0 , sum2 = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { A [ int ( str [ i ] ) - 48 ] ++ ; } for ( int i = 0 ; i <= 9 ; i ++ ) { if ( i % 2 != 0 ) { sum1 = sum1 + A [ i ] ; } else { sum2 = sum2 + A [ i ] ; } } if ( sum1 == sum2 ) { cout << " - 1" ; } else if ( sum1 > sum2 ) { cout << " Player ▁ 1" ; } else { cout << " Player ▁ 2" ; } } int main ( ) { string str = "78787" ; determineWinner ( str ) ; return 0 ; }