Sign in with Google

Google will share your name, email, and profile picture with DevExCode. See our privacy policy.

LeetCode 877: Stone Game

LeetCode 877 Solution Explanation

Explanation:

To solve this problem, we can use dynamic programming. We can create a 2D dp array where dp[i][j] represents the maximum number of stones one player can collect from piles[i] to piles[j] if both players play optimally.

At each step, we need to consider two scenarios:

  1. If Alice takes piles[i], the maximum number of stones she can collect is piles[i] + dp[i+1][j] (since Bob will play optimally to maximize his stones from the remaining piles).
  2. If Alice takes piles[j], the maximum number of stones she can collect is piles[j] + dp[i][j-1].

Both players aim to maximize the number of stones they collect, so Alice wants to maximize her number of stones at the end, which means she wants to maximize the difference between her stones and Bob's stones. If the difference is positive, Alice wins.

After filling up the dp array, we check if dp[0][n-1] (where n is the number of piles) is greater than 0, indicating that Alice wins.

Time Complexity: O(n^2) where n is the number of piles
Space Complexity: O(n^2)

:

LeetCode 877 Solutions in Java, C++, Python

class Solution {
    public boolean stoneGame(int[] piles) {
        int n = piles.length;
        int[][] dp = new int[n][n];

        for (int i = 0; i < n; i++) {
            dp[i][i] = piles[i];
        }

        for (int len = 2; len <= n; len++) {
            for (int i = 0; i <= n - len; i++) {
                int j = i + len - 1;
                dp[i][j] = Math.max(piles[i] - dp[i + 1][j], piles[j] - dp[i][j - 1]);
            }
        }

        return dp[0][n - 1] > 0;
    }
}

Interactive Code Editor for LeetCode 877

Improve Your LeetCode 877 Solution

Use the editor below to refine the provided solution for LeetCode 877. Select a programming language and try the following:

  • Add import statements if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.

Loading editor...

Related LeetCode Problems