#486
Medium Algorithms Predict the winner
Array Math Dynamic Programming Recursion Game Theory
56.1% acceptance
Jan 13, 2026
6152
295
You are given an integer array nums. Two players are playing a game with this array: player 1 and player 2.
Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of 0. At each turn, the player takes one of the numbers from either end of the array (i.e., nums[0] or nums[nums.length - 1]) which reduces the size of the array by 1. The player adds the chosen number to their score. The game ends when there are no more elements in the array.
Return true if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return true. You may assume that both players are playing optimally.
Solution
Rust
Time O(n)
Space O(n)
use std::collections::HashMap;
impl Solution {
pub fn predict_the_winner(nums: Vec<i32>) -> bool {
let mut memo = HashMap::new();
Self::helper(&nums, 0, nums.len() - 1, &mut memo) >= 0
}
fn helper(nums: &[i32], left: usize, right: usize, memo: &mut HashMap<(usize, usize), i32>) -> i32 {
if left == right { return nums[left]; }
if let Some(&val) = memo.get(&(left, right)) { return val; }
let pick_left = nums[left] - Self::helper(nums, left + 1, right, memo);
let pick_right = nums[right] - Self::helper(nums, left, right - 1, memo);
let result = pick_left.max(pick_right);
memo.insert((left, right), result);
result
}
}