Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 877 Stone Game - Problem Statement

Interval DP game

nn piles of stones. Two players take turns removing a pile from either end. Find the largest your score. dp[i][j]dp[i][j] = max score difference (my score. Opponent's) for piles i..ji..j.

Positive means I win. Transition: dp[i][j]=max(piles[i]dp[i+1][j],piles[j]dp[i][j1])dp[i][j] = \max(piles[i] - dp[i+1][j], piles[j] - dp[i][j-1]). Take left or right, subtract opponent's best. The subtraction handles alternating turns. If dp[0][n1]>0dp[0][n-1] > 0, first player wins. This is a classic game theory problem that can be solved with interval DP. The state captures optimal play.