Sponsored
Sponsored
This approach uses a straightforward observation: since Alice starts first and can always choose the better pile (since the number of piles is even and both play optimally), Alice will always have the advantage. Thus, Alice can always ensure she ends up with more stones than Bob by always picking the piles in a manner that maximizes her total stones. Therefore, the solution can be returned directly as true without sophisticated calculations.
Time Complexity: O(1) - The solution involves a direct return statement.
Space Complexity: O(1) - No additional space is used.
1int stoneGame(int* piles, int pilesSize) {
2 return 1;
3}
4
In C, the function stoneGame
simply returns 1 (true) since Alice is guaranteed to win.
The dynamic programming approach involves calculating the maximum stones a player can gather from any given state, thus determining the optimal strategy. We can define a DP table where dp[i][j]
represents the maximum number of stones a player can get from piles i
to j
inclusive. The formula to update the DP table is determined by considering the take from left or right scenarios. In the end, Alice wins if dp[0][n-1]
is greater than half of the total stones, ensuring her strategy leads to a win.
Time Complexity: O(n^2) - We fill an n by n table.
Space Complexity: O(n^2) - Additional space for the table.
int n = piles.size();
vector<vector<int>> dp(n, vector<int>(n, 0));
for (int i = 0; i < n; i++) {
dp[i][i] = piles[i];
}
for (int length = 2; length <= n; length++) {
for (int i = 0; i <= n - length; i++) {
int j = i + length - 1;
dp[i][j] = max(piles[i] - dp[i + 1][j], piles[j] - dp[i][j - 1]);
}
}
return dp[0][n - 1] > 0;
}
The C++ solution defines the function stoneGame
, implementing a DP approach to track outcomes and decide if Alice's first move is decisive for victory.