Skip to main content
Back to problems
#1140
Medium Algorithms

Stone game ii

Array Math Dynamic Programming Prefix Sum Game Theory
72.9% acceptance
Feb 25, 2026
3438
938
Alice and Bob continue their games with piles of stones. There are a number of piles arranged in a row, and each pile has a positive integer number of stones piles[i]. The objective of the game is to end with the most stones. Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take all the stones in the first X remaining piles, where 1 <= X <= 2M. Then, we set M = max(M, X). Initially, M = 1. The game continues until all the stones have been taken. Assuming Alice and Bob play optimally, return the maximum number of stones Alice can get.

Solution

Rust
Time O(n * m)
Space O(n * m)
LeetCode
solution.rs
impl Solution {
  pub fn stone_game_ii(piles: Vec<i32>) -> i32 {
    let n = piles.len();
    let mut suffix = vec![0i32; n + 1];
    for i in (0..n).rev() {
      suffix[i] = suffix[i + 1] + piles[i];
    }
    // dp[i][m] = max stones current player can get from piles[i..] with M=m
    let mut dp = vec![vec![0i32; n + 1]; n + 1];
    for i in (0..n).rev() {
      for m in 1..=n {
        for x in 1..=(2 * m).min(n - i) {
          dp[i][m] = dp[i][m].max(suffix[i] - dp[i + x][m.max(x)]);
        }
      }
    }
    dp[0][1]
  }
}