参考了:
(1)点击打开链接
(2)点击打开链接
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size() == 0){
return 0;
}
int g[3] = {0} , l[3] = {0};
//g[0],l[0]始终为0
//这里的i代表到达当前天数,也就是到达当前位置
for(int i = 0 ; i < prices.size()-1 ;i++){
int diff = prices[i+1] - prices[i];
for(int j = 2 ; j >= 1 ; j--){
//j代表次数,为何先计算j=2,可以看到j=2时,l[j] = max(g[2-1]+max(diff , 0) , l[j] + diff)
//注意g[2-1] = g[1] 也就是l[2]可能是前一次的g[1]与max(diff , 0)的和,如果先计算j = 1 的话 g[1] 就会被新的值覆盖,g[1] = max(g[1],l[1]),而此时的l[1]是由 l[1] = max(g[1-1] + max(diff , 0) , l[1] + diff)计算得来,而g[1-1] = g[0]始终就是0,不是基于全局的最优解。
l[j] = max(g[j-1] + max(diff , 0) , l[j] + diff);
g[j] = max(l[j],g[j]);
}
}
return max(g[1],g[2]);
}
};