Friday, July 28th

 Can player 1 win?

Two players are in a game.  The game has an array.  At each turn, beginning with player 1, a player selects a value from the beginning or end of the array.  The value is added to the player's score.  Each selection reduces the size of the array by 1.  After all values have been selected, the player with the highest score wins.  Return true if planer 1 can with the game.


One key observation is that it's not asking for a maximum or minimum like most dp problems, but it's looking to see if player 1 can win.  Victory can be determined by the difference in scores.

Also, a player can choose either the right or the left value.  This leads to the dp recurrence relation:

    int sl = ns[l] - dp(l+1,r);
int sr = ns[r] - dp(l,r-1);

This is because each side is trying to optimize their playing.  The difference in the score becomes what they choose (whether the left or the right), then that total subtracted from what the other player will do.

Full code:
vector<vector<int> > memo;
vector<int> ns;

int dp(int l, int r) {
if(memo[l][r]!=INT_MIN) {
return memo[l][r];
}
if(l==r) {
return ns[l];
}

int sl = ns[l] - dp(l+1,r);
int sr = ns[r] - dp(l,r-1);

memo[l][r]=max(sl,sr);

return memo[l][r];
}

bool PredictTheWinner(vector<int>& nums) {
ns=nums;
int n=ns.size();
memo=vector<vector<int> >(n, vector<int>(n,INT_MIN));

return dp(0,n-1) >= 0;
}

Shout out to the Editorial for clearing up how the score difference can be applied to a dynamic programming problem like Max Score Performing Multiplies

Comments

Popular posts from this blog

Wednesday, September 20th

Monday, September 11th

Tuesday, September 19th