首页 > 代码库 > [Leetcode] DP-- 486. Predict the Winner
[Leetcode] DP-- 486. 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 1:
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.
Example 2:
Input: [1, 5, 233, 7] Output: True Explanation: Player 1 first chooses 1. Then player 2 have to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.
Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.
Solution:
1 def predictHelper(nums, sum1, sum2, player): 2 if len(nums) == 0: 3 return sum1 >= sum2 4 if len(nums) == 1: 5 if player == 1: 6 return (sum1 + nums[0] >= sum2) 7 elif player == 2: 8 return (sum2 + nums[0] > sum1) 9 10 tmpNums1 = nums[1::] 11 tmpNums2 = nums[0:len(nums)-1] 12 #print ("sum1, sum2: ", sum1, sum2, nums) 13 if player == 1: 14 return not predictHelper(tmpNums1, sum1+nums[0], sum2, 2) or not predictHelper(tmpNums2, sum1+nums[-1], sum2, 2) 15 elif player == 2: 16 return not predictHelper(tmpNums1, sum1, sum2+nums[0], 1) or not predictHelper(tmpNums2, sum1, sum2+nums[-1], 1) 17 18 sum1 = 0 19 sum2 = 0 20 player = 1 21 return predictHelper(nums, sum1, sum2, player)
2. we consider the difference or player 1 and player 2. another recursive way is designed:
1 def predictHelper(nums, start, end): 2 if start == end: 3 return nums[start] 4 else: 5 return max(nums[start] - predictHelper(nums, start+1, end), nums[end] - predictHelper(nums, start, end-1)) 6 return predictHelper(nums, 0, len(nums)-1) >= 0
It has TLE problem, without memoization
3. use DP memoization
dp[i][j] indicates the maximum point obtained from index i to j
transition function: dp[i][j]=max(nums[i]-dp[i+1][j], nums[j]-dp[i][j-1]) 。
initialize dp[i][i] = 0
1 if nums is None or len(nums) == 0: 2 return false 3 dp = [[0]* len(nums) for _ in range(0, len(nums))] 4 5 for i in range(len(nums)): 6 dp[i][i] = 0 7 8 for i in range(len(nums)-2, -1, -1): 9 for j in range(i+1, len(nums), 1): 10 dp[i][j] = max(nums[i] - dp[i+1][j], nums[j]-dp[i][j-1]) 11 12 return dp[0][len(nums)-1] >= 0
[Leetcode] DP-- 486. Predict the Winner