-
Notifications
You must be signed in to change notification settings - Fork 0
/
122_buySellStock.cpp
47 lines (34 loc) · 931 Bytes
/
122_buySellStock.cpp
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
#include <iostream>
#include <vector>
using namespace std;
int maxProfit(vector<int> prices)
{
// int profit = 0;
// int size = prices.size();
// for (int i = 0; i != size - 1; ++i) {
// if (prices[i+1] > prices[i]) {
// profit += prices[i+1] - prices[i];
// }
// }
// return profit;
// DP
int size = prices.size();
if (0 == size) {
return 0;
}
int profit = 0;
vector<vector<int>> result(size, vector<int>(2, 0));
result[0][0] = 0;
result[0][1] = -prices[0];
for (int i = 1; i != size; ++i) {
result[i][0] = std::max(result[i-1][0], result[i-1][1] + prices[i]);
result[i][1] = std::max(result[i-1][1], result[i-1][0] - prices[i]);
}
return result[size-1][0];
}
int main(int argc, char const *argv[])
{
vector<int> prices = {7, 1, 5, 3, 6, 4};
cout << maxProfit(prices) << endl;
return 0;
}