Predict the Winner — LeetCode 486 Python Solution
MediumRecursionArrayMathDynamic ProgrammingGame Theory
- Problem
- #486
- Pattern
- Dynamic Programming
- 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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(n^2) |
| Space | O(n^2) auxiliary |
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
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(n^2).
- What is the space complexity of LeetCode 486. Predict the Winner?
- The Python solution on this page uses O(n^2) 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.