LeetCode 877: Stone Game Solution

Master LeetCode problem 877 (Stone Game), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

Problem 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)

:

Solution Code

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;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 877 (Stone Game)?

This page provides optimized solutions for LeetCode problem 877 (Stone Game) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 877 (Stone Game)?

The time complexity for LeetCode 877 (Stone Game) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 877 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 877 in Java, C++, or Python.

Back to LeetCode Solutions