[LeetCode] Stone Game III

1406. Stone Game III

Alice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue.

Alice and Bob take turns, with Alice starting first. On each player’s turn, that player can take 1, 2, or 3 stones from the first remaining stones in the row.

The score of each player is the sum of the values of the stones taken. The score of each player is 0 initially.

The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken.

Assume Alice and Bob play optimally.

Return “Alice” if Alice will win, “Bob” if Bob will win, or “Tie” if they will end the game with the same score.

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
34
35
36
37
38
39
class Solution {
vector<vector<pair<int, int>>> dp;
pair<int, int> solution(vector<int>& st, int p, bool alice) {
if(p == st.size()) return {0,0};
if(dp[alice][p].first != INT_MIN) return dp[alice][p];
int sum = st[p];
pair<int,int>& res = dp[alice][p] = solution(st, p+1, !alice);
if(alice) {
res.first += sum;
} else {
res.second += sum;
}

for(int i = p+1; i < st.size() and i <= p + 2; i++) {
sum += st[i];
if(alice) {
auto [nextAlice, nextBob] = solution(st,i+1,!alice);
int aliceSum = nextAlice + sum;
if(aliceSum - nextBob > res.first - res.second) {
res = {aliceSum, nextBob};
}
} else {
auto [nextAlice, nextBob] = solution(st,i+1,!alice);
int bobSum = nextBob + sum;
if(bobSum - nextAlice > res.second - res.first) {
res = {nextAlice, bobSum};
}
}
}
return res;
}
public:
string stoneGameIII(vector<int>& stoneValue) {
dp = vector<vector<pair<int,int>>> (2,vector<pair<int,int>>(stoneValue.size(), {INT_MIN,INT_MIN}));
auto [aliceSum, bobSum] = solution(stoneValue,0,true);

return aliceSum > bobSum ? "Alice" : bobSum > aliceSum ? "Bob" : "Tie";
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/11/PS/LeetCode/stone-game-iii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.