[LeetCode] Stone Game VII

1690. Stone Game VII

Alice and Bob take turns playing a game, with Alice starting first.

There are n stones arranged in a row. On each player’s turn, they can remove either the leftmost stone or the rightmost stone from the row and receive points equal to the sum of the remaining stones’ values in the row. The winner is the one with the higher score when there are no stones left to remove.

Bob found that he will always lose this game (poor Bob, he always loses), so he decided to minimize the score’s difference. Alice’s goal is to maximize the difference in the score.

Given an array of integers stones where stones[i] represents the value of the ith stone from the left, return the difference in Alice and Bob’s score if they both play optimally.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
int dp[1010][1010];
int helper(vector<int>& A, int l, int r) {
if(l == r) return 0;
if(dp[l][r] != -1) return dp[l][r];
int& res = dp[l][r] = 0;

res = max(res, A[r + 1] - A[l + 1] - helper(A, l + 1, r));
res = max(res, A[r] - A[l] - helper(A, l, r - 1));

return res;
}
public:
int stoneGameVII(vector<int>& stones) {
vector<int> psum{0};
memset(dp, -1, sizeof dp);
for(auto& n : stones) psum.push_back(n + psum.back());
return helper(psum, 0, stones.size() - 1);
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/01/PS/LeetCode/stone-game-vii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.