MediumNo. 0486
Predict the Winner — LeetCode 486 Python Solution
- Pattern
- Dynamic Programming
- Topics
- Recursion, Array, Math, Dynamic Programming, Game Theory
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given an integer array nums. Two players are playing a game with this array: player 1 and player 2.
Example
- Input
- nums = [1,5,2]
- Output
- false
- Explanation
- Initially, player 1 can choose between 1 and 2.
Python solution
class Solution:
def predictTheWinner(self, nums: List[int]) -> bool:
@cache
def dfs(i: int, j: int) -> int:
if i > j:
return 0
return max(nums[i] - dfs(i + 1, j), nums[j] - dfs(i, j - 1))
return dfs(0, len(nums) - 1) >= 0Complexity
- Time
- O(n2)
- Space · auxiliary
- O(n2)
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 486. Predict the Winner is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0877 | Stone Game | Medium |
| 1140 | Stone Game II | Medium |
| 1406 | Stone Game III | Hard |
| 1563 | Stone Game V | Hard |
| 1690 | Stone Game VII | Medium |
| 1728 | Cat and Mouse II | Hard |
Frequently asked questions
- How hard is LeetCode 486. Predict the Winner?
LeetCode 486. Predict the Winner is rated Medium on LeetCode.
- What is the time complexity of LeetCode 486. Predict the Winner?
The Python solution on this page runs in O(n2).
- What is the space complexity of LeetCode 486. Predict the Winner?
The Python solution on this page uses O(n2) auxiliary space.
- What topics does LeetCode 486. Predict the Winner cover?
LeetCode 486. Predict the Winner is tagged Recursion, Array, Math, Dynamic Programming and Game Theory on LeetCode.