-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlintcode995.cpp
More file actions
30 lines (27 loc) · 880 Bytes
/
lintcode995.cpp
File metadata and controls
30 lines (27 loc) · 880 Bytes
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
class Solution {
public:
/**
* @param prices: a list of integers
* @return: return a integer
*/
int maxProfit(vector<int> &prices) {
int n = prices.size();
if(n <= 1)
return 0;
/**
* dp[i][0]:第i天未持有股票的最大利益
* dp[i][1]:第i天持有股票的最大利益
* 狀態轉移方程
* dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
* dp[i][1] = max(dp[i][1], dp[i - 2][0] - prices[i]);
*/
int not_hold = 0, hold = -prices[0], prev_not_hold = 0;
for(int i = 0; i < n; ++i) {
int tmp = not_hold;
not_hold = max(not_hold, hold + prices[i]);
hold = max(hold, prev_not_hold - prices[i]);
prev_not_hold = tmp;
}
return not_hold;
}
};