forked from Chayandas07/LeetCode-challenge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1406. Stone Game III
53 lines (44 loc) · 1.53 KB
/
1406. Stone Game III
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class Solution {
public:
// For retrieving the sum of piles between l to r
int get(int l, int r, vector<long long> &pref)
{
return pref[r + 1] - pref[l];
}
int help(int idx, bool aliceTurn, vector<long long> &pref, vector<int> &piles, vector<vector<int>> &dp)
{
if (idx >= piles.size())
return 0;
if (dp[idx][aliceTurn] != -1)
return dp[idx][aliceTurn];
if (aliceTurn)
{
// changed to -inf because here we can have negative values also.
int ans = -1e9;
for (int x = 1; x <= 3; x++)
if (idx + x - 1 < piles.size())
ans = max(ans, get(idx, idx + x - 1, pref) + help(idx + x, false, pref, piles, dp));
return dp[idx][aliceTurn] = ans;
}
int ans = 1e9;
for (int x = 1; x <= 3; x++)
if (idx + x - 1 < piles.size())
ans = min(ans, help(idx + x, true, pref, piles, dp));
return dp[idx][aliceTurn] = ans;
}
string stoneGameIII(vector<int> &stoneValue)
{
int n = stoneValue.size();
vector<long long> pref(n + 1, 0);
for (int i = 1; i <= n; i++)
pref[i] = pref[i - 1] + stoneValue[i - 1];
vector<vector<int>> dp(n + 1, vector<int>(2, -1));
int alice = help(0, true, pref, stoneValue, dp);
int bob = pref.back() - alice;
if (alice > bob)
return "Alice";
else if (alice < bob)
return "Bob";
return "Tie";
}
};