[LeetCode] Stone Game V

1563. Stone Game V

There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue.

In each round of the game, Alice divides the row into two non-empty rows (i.e. left row and right row), then Bob calculates the value of each row which is the sum of the values of all the stones in this row. Bob throws away the row which has the maximum value, and Alice’s score increases by the value of the remaining row. If the value of the two rows are equal, Bob lets Alice decide which row will be thrown away. The next round starts with the remaining row.

The game ends when there is only one stone remaining. Alice’s is initially zero.

Return the maximum score that Alice can obtain.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
int dp[501][501];
int dfs(vector<int>& prefixSum, int l, int r) {
if(l + 1 > r) return 0;
if(dp[l][r] != -1) return dp[l][r];
dp[l][r] = 0;
vector<int> choose;
int maxMinValue = 0;

for(int i = l; i < r; i++) {
int left = prefixSum[i + 1] - prefixSum[l], right = prefixSum[r + 1] - prefixSum[i + 1];
if(left >= right) {
dp[l][r] = max(dp[l][r], dfs(prefixSum, i + 1, r) + right);
}

if(right >= left) {
dp[l][r] = max(dp[l][r], dfs(prefixSum, l, i) + left);
}
}

return dp[l][r];
}
public:
int stoneGameV(vector<int>& stoneValue) {
memset(dp, -1, sizeof(dp));
vector<int> prefixSum {0};
for(auto& st : stoneValue) {
prefixSum.push_back(prefixSum.back() + st);
}

return dfs(prefixSum, 0, stoneValue.size() - 1);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/01/31/PS/LeetCode/stone-game-v/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.