Skip to content

Commit 6c08280

Browse files
authored
Create stone-game-ii.cpp
1 parent c25c12e commit 6c08280

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

C++/stone-game-ii.cpp

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// Time: O(n*(logn)^2)
2+
// Space: O(nlogn)
3+
4+
class Solution {
5+
public:
6+
int stoneGameII(vector<int>& piles) {
7+
for (int i = piles.size() - 2; i >= 0; --i) {
8+
piles[i] += piles[i + 1];
9+
}
10+
unordered_map<int, unordered_map<int, int>> lookup;
11+
return dp(piles, &lookup, 0, 1);
12+
}
13+
14+
private:
15+
int dp(const vector<int>& piles,
16+
unordered_map<int, unordered_map<int, int>> *lookup,
17+
int i, int m) {
18+
if (i + 2 * m >= piles.size()) {
19+
return piles[i];
20+
}
21+
if (!lookup->count(i) || !(*lookup)[i].count(m)) {
22+
int min_dp = numeric_limits<int>::max();
23+
for (int x = 1; x <= 2 * m; ++x) {
24+
min_dp = min(min_dp, dp(piles, lookup, i + x, max(m, x)));
25+
}
26+
(*lookup)[i][m] = piles[i] - min_dp;
27+
}
28+
return (*lookup)[i][m];
29+
}
30+
};

0 commit comments

Comments
 (0)