Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 486 Predict the Winner - Walkthrough

Tracing the game

Two players pick from ends of [1,5,2][1, 5, 2]. Each tries to find the largest their score. Who wins? dp[i][j]dp[i][j] = net advantage (my score. Opponent's) for interval [i,j][i,j].

Player 1 wants positive, Player 2 wants negative (or zero). dp[0][0]=1dp[0][0]=1, dp[1][1]=5dp[1][1]=5, dp[2][2]=2dp[2][2]=2. For dp[0][1]dp[0][1]: take 1 and face dp[1][1]=5-dp[1][1]=-5, or take 5 and face dp[0][0]=1-dp[0][0]=-1. Best: 51=45-1=4. For dp[0][2]dp[0][2]: take 1 and face dp[1][2]-dp[1][2], or take 2 and face dp[0][1]-dp[0][1]. After computing: Player 1 wins if dp[0][n1]0dp[0][n-1] \geq 0.