You are given an array of integers nums
. Two players take turns, picking either the first or last element from the array, removing it, and gaining the number of points equal to the value of the element they picked. The game ends when there are no more elements to pick.
Given an array of scores, predict whether Player 1 is the winner. If Player 1 wins, return True
. If Player 1 loses or the game ends in a draw, return False
.
Player 1 always starts first, and both players try to maximize their score.
nums
?
False
.The problem can be approached using a recursive dynamic programming algorithm. We need to keep track of the scores that both players can achieve. To do this, we use memoization to avoid recalculating results for the same subproblems.
Here’s a breakdown of the approach:
score_diff(l, r)
that returns the maximum score difference between Player 1 and Player 2 when they play optimally on the subarray nums[l:r+1]
.l == r
, which means only one element is left.def PredictTheWinner(nums):
def score_diff(l, r):
if l == r:
return nums[l]
if (l, r) in memo:
return memo[(l, r)]
pick_left = nums[l] - score_diff(l + 1, r)
pick_right = nums[r] - score_diff(l, r - 1)
memo[(l, r)] = max(pick_left, pick_right)
return memo[(l, r)]
n = len(nums)
memo = {}
return score_diff(0, n - 1) >= 0
# Example usage:
nums = [1, 5, 233, 7]
print(PredictTheWinner(nums)) # Output: True
The time complexity of this approach is O(n^2)
because:
score_diff(l, r)
potentially evaluates each subarray only once (thanks to memoization),O(n^2)
possible pairs of (l, r)
.The space complexity is O(n^2)
due to the storage required for memoization.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?