[LeetCode] Predict the Winner

486. Predict the Winner

You are given an integer array nums. Two players are playing a game with this array: player 1 and player 2.

Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of 0. At each turn, the player takes one of the numbers from either end of the array (i.e., nums[0] or nums[nums.length - 1]) which reduces the size of the array by 1. The player adds the chosen number to their score. The game ends when there are no more elements in the array.

Return true if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return true. You may assume that both players are playing optimally.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
int dp[21][21];
int helper(vector<int>& nums, int l, int r, bool turn) {
if(l == r) {
return turn ? nums[l] : -nums[l];
}
if(dp[l][r] != -1) return dp[l][r];
dp[l][r] = 0;
if(turn) {
dp[l][r] = max(helper(nums, l + 1, r, !turn) + nums[l], helper(nums,l, r - 1, !turn) + nums[r]);
} else {
dp[l][r] = min(helper(nums, l + 1, r, !turn) - nums[l], helper(nums,l, r - 1, !turn) - nums[r]);
}
return dp[l][r];
}
public:
bool PredictTheWinner(vector<int>& nums) {
memset(dp,-1,sizeof(dp));
return helper(nums,0,nums.size() - 1, true) >= 0;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/21/PS/LeetCode/predict-the-winner/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.