Predict the Winner
Given an array of scores that are non-negative integers. Player 1 picks one of the numbers from either end of the array followed by the player 2 and then player 1 and so on. Each time a player picks a number, that number will not be available for the next player. This continues until all the scores have been chosen. The player with the maximum score wins.
Given an array of scores, predict whether player 1 is the winner. You can assume each player plays to maximize his score.
Example
Input: [1, 5, 2]
Output: False
Explanation: Initially, player 1 can choose between 1 and 2.
If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2).
So, final score of player 1 is 1 + 2 = 3, and player 2 is 5.
Hence, player 1 will never be the winner and you need to return False.
Solution
// 很巧妙的dp数组构造,二维i、j标识数组两端
class Solution:
def PredictTheWinner(self, nums: List[int]) -> bool:
n = len(nums)
if n==1 or n%2==0: return True
dp = [[0]*n for _ in range(n)]
for i in range(n-1, -1, -1):
for j in range(i+1, n):
dp[i][j] = max(nums[i]-dp[i+1][j], nums[j]-dp[i][j-1])
return dp[0][-1]>=0