forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain2.cpp
More file actions
49 lines (36 loc) · 1.21 KB
/
Copy pathmain2.cpp
File metadata and controls
49 lines (36 loc) · 1.21 KB
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
/// Source : https://leetcode.com/problems/stone-game/description/
/// Author : liuyubobobo
/// Time : 2018-08-02
#include <iostream>
#include <vector>
using namespace std;
/// Dynamic Programming
/// Time Complexity: O(n^2)
/// Space Complexity: O(n^2)
class Solution {
public:
bool stoneGame(vector<int>& piles) {
int n = piles.size();
vector<vector<vector<int>>> dp(2, vector<vector<int>>(n, vector<int>(n, -1)));
for(int i = 0 ; i < n ; i ++){
dp[0][i][i] = piles[i];
dp[1][i][i] = -piles[i];
}
for(int sz = 2 ; sz <= n ; sz ++)
for(int i = 0; i + sz - 1 < n ; i ++){
dp[0][i][i + sz - 1] = max(piles[i] + dp[1][i + 1][i + sz - 1],
piles[i + sz - 1] + dp[1][i][i + sz - 2]);
dp[1][i][i + sz - 1] = max(-piles[i] + dp[0][i + 1][i + sz - 1],
-piles[i + sz - 1] + dp[0][i][i + sz - 2]);
}
return dp[0][0][n - 1];
}
};
void print_bool(bool res){
cout << (res ? "True" : "False") << endl;
}
int main() {
vector<int> piles1 = {5, 3, 4, 5};
print_bool(Solution().stoneGame(piles1));
return 0;
}