Skip to content

Commit efaa647

Browse files
Added 486 leetcode solution Predict the winner cpp
1 parent a4f6551 commit efaa647

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

486. Leetcode Predict the Winner.cpp

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
2+
/* Approach: As both the players are equally strong, both will try to reduce the possibility of winning of each
3+
other. Now let’s see how the opponent can achieve this.
4+
5+
There are two choices:
6+
7+
The user chooses the ‘ith’ coin with value ‘Vi’: The opponent either chooses (i+1)th coin or jth coin.
8+
The opponent intends to choose the coin which leaves the user with minimum value.
9+
i.e. The user can collect the value Vi + min(F(i+2, j), F(i+1, j-1) ).
10+
11+
coinGame1
12+
13+
The user chooses the ‘jth’ coin with value ‘Vj’: The opponent either chooses ‘ith’ coin or ‘(j-1)th’ coin.
14+
The opponent intends to choose the coin which leaves the user with minimum value, i.e. the user can
15+
collect the value Vj + min(F(i+1, j-1), F(i, j-2) ).
16+
*/
17+
18+
19+
20+
21+
class Solution {
22+
public:
23+
int dp[30][30];
24+
int find(int l,int r,vector<int>& v){
25+
if(dp[l][r]!=-1)return dp[l][r];
26+
if(l==r)return dp[l][r]=v[l];
27+
if(r==l+1)return dp[l][r]=max(v[l],v[r]);
28+
return dp[l][r]=max(v[l] + min(find(l+2,r,v), find(l+1,r-1,v) ), v[r] + min( find(l,r-2,v), find(l+1,r-1,v) ) );
29+
}
30+
bool PredictTheWinner(vector<int>& nums) {
31+
memset(dp,-1,sizeof(dp));
32+
int n=nums.size();
33+
int s=accumulate(nums.begin(),nums.end(),0);
34+
int a=find(0,n-1,nums)*2;
35+
return (a>=s)?true:false;
36+
}
37+
};

0 commit comments

Comments
 (0)