Sorry, I have no idea yet about how to solve this problem with a one-dimensional array right now. Maybe I’ll follow up at another time ?.
I think the most important points as following:
Transformation equation && What dp[i]/dp[i][j] stand for ?. Firstly, we need to find out the relationship (Transformation equation) between DP (maybe is a one-dimensional or a two-dimensional array) and the next one, but if we don’t know what DP[i] or DP[i][j] denotes for, we can’t find out the relationship immediately. So, it is a complex process,we need to keep trying. If DP decided by two factors, then DP is a two-dimensional array. In this case, dp[i][j] stands for the differ of stones between the first player and the second player when it’s still left stones whose indices are between i and j.
Code
#include <iostream>
#include <vector>
#include <string.h>
using namespace std;
// Mine Version
bool stoneGame2(vector<int>& piles) {
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 slantLine = 1; slantLine < n; slantLine++) {
for (int i=0, j=slantLine; i<n && j<n; i++, j++) {
if ( (i+j) % 2 != 0 ) { // the first player, cause the count of piles is even
dp[i][j] = max(dp[i+1][j] + piles[i], dp[i][j-1] + piles[j]); // pick stones from i...j, you can choose piles[i] or piles[j]
} else { // the second player
dp[i][j] = min(dp[i+1][j] - piles[i], dp[i][j-1] - piles[j]); // subtract the second player's stones.
}
}
}
for (int i=0; i<n; i++) {
for (int j=0; j<n; j++) {
cout << dp[i][j] << " ";
}
cout << endl;
}
return dp[0][n-1];
}
// Offical Version
bool stoneGame1(vector<int>& piles) {
int N = piles.size();
// dp[i+1][j+1] = the value of the game [piles[i], ..., piles[j]]
int dp[N+2][N+2];
memset(dp, 0, sizeof(dp));
for (int size = 1; size <= N; ++size)
for (int i = 0, j = size - 1; j < N; ++i, ++j) {
int parity = (j + i + N) % 2; // j - i - N; but +x = -x (mod 2)
if (parity == 1)
dp[i+1][j+1] = max(piles[i] + dp[i+2][j+1], piles[j] + dp[i+1][j]);
else
dp[i+1][j+1] = min(-piles[i] + dp[i+2][j+1], -piles[j] + dp[i+1][j]);
}
for (int i=0; i<N+2; i++) {
for (int j=0; j<N+2; j++) {
cout << dp[i][j] << " ";
}
cout << endl;
}
return dp[1][N] > 0;
}
int main() {
vector<int> piles = {5, 3, 4, 5};
cout << "Official Version" << endl;
stoneGame1(piles);
cout<<endl;
cout << "Mine" << endl;
stoneGame2(piles);
return 0;
}
Conclusion
It’s important to consider the transformation equation ?.
CatalogueDescriptionThinkingCodeConclusionDescriptionThinkingSorry, I have no idea yet about how to solve this problem with a one-dimensional array right now. Maybe I’ll follow up at another time ...