Diagonal

394t. Coins in a Line

There are n coins in a line. Two players take turns to take one or two coins from right side until there are no more coins left. The player who take the last coin wins.

Could you please decide the first play will win or lose?

/**
 * Statement: dp[i], when i coins last, if the person now taking the coin could win
 * Func: dp[i] = true if dp[i-1] or dp[i-2] is false
 * Init: dp[0] = false, dp[1] = true;
 * Ans: dp[n]
 * 
 */
public boolean firstWillWin(int n) {
    if(n==0) return false;
    if(n==1) return true;

    boolean[] dp = new boolean[n+1];

    dp[0] = false;
    dp[1] = true;

    for(int i=2; i<=n; i++){
        if(dp[i-1]==false || dp[i-2]==false) dp[i] = true;
    }

    return dp[n];
}

395t Coin In Line II

There are n coins with different value in a line. Two players take turns to take one or two coins from left side until there are no more coins left. The player who take the coins with the most value wins.

Could you please decide the first player will win or lose?

486. Predict the Winner(由下往上更新)

An array of numbers, 2 players take pile from each side by turns. Return if player 1 can win

  • State: dp[i][j] = pick from nums[i] to nums[j], the number you has more than competitor

  • Func: dp[i][j] = max(nums[i] - dp[i+1][j], nums[j] - dp[i][j-1])

  • Ans: if dp[0][n-1] > 0

Explain

  • 1D space solution

877 Stone Game(對角線更新)

A pile of stones, 2 players take pile from each side by turns. Return if player 1 has more stones

  • State: dp[i][j] = pick from piles[i] to piles[j], the stone you has more than competitor

  • Func: dp[i][j] = max(p[i] - dp[i+1][j], p[j] - dp[i][j-1])

  • Init: dp[i][i] = p[i];

  • Ans: if dp[0][n-1] > 0

Last updated

Was this helpful?