Skip to content

Commit 573c022

Browse files
authored
Create stone-game.cpp
1 parent 04e3e12 commit 573c022

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

C++/stone-game.cpp

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// Time: O(n^2)
2+
// Space: O(n)
3+
4+
// The solution is the same as https://leetcode.com/problems/predict-the-winner/description/
5+
class Solution {
6+
public:
7+
bool stoneGame(vector<int>& piles) {
8+
if (piles.size() % 2 == 0 || piles.size() == 1) {
9+
return true;
10+
}
11+
12+
vector<int> dp(piles.size());
13+
for (int i = piles.size() - 1; i >= 0; --i) {
14+
dp[i] = piles[i];
15+
for (int j = i + 1; j < piles.size(); ++j) {
16+
dp[j] = max(piles[i] - dp[j], piles[j] - dp[j - 1]);
17+
}
18+
}
19+
20+
return dp.back() >= 0;
21+
}
22+
};
23+

0 commit comments

Comments
 (0)