#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
// 方法一:暴力求解法,深度优先搜索,遍历所有情况,通过199/201条用例,出现TLE问题
class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.size() < 2) return 0;
int max = 0,sum = 0, i = 0,flag = -1; // 1 means sell, -1 means buy
bool cooldown = false;
CalculateProfit(max, i, flag, sum, prices, cooldown);
return max;
}
void CalculateProfit(int& max, int index, int flag, int sum, vector<int>& prices, bool cooldown) {
if (index >= prices.size()) return;
if (cooldown == true) {
CalculateProfit(max, index + 1, -1, sum, prices, false);
return;
}
// ought to buy
if (flag == -1) {
// don't buy this term
CalculateProfit(max, index + 1, -1, sum, prices, false);
// buy this term
sum += prices[index] * flag;
max = sum > max ? sum : max;
CalculateProfit(max, index + 1, 1, sum, prices, false);
}
// ought to sell
if (flag == 1)
{
// don't sell this term
CalculateProfit(max, index + 1, 1, sum, prices, false);
// sell this term
sum += prices[index] * flag;
sum = sum < 0 ? 0 : sum;
max = sum > max ? sum : max;
CalculateProfit(max, index + 1, -1, sum, prices, true);
}
}
};
// 方法二,动态规划(一维三因素动态规划),难在数字关系推导,理清三种状态的计算过程
class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.size() < 2) return 0;
vector<int> sell, buy, cool;
sell.push_back(0);
buy.push_back(-prices[0]);
cool.push_back(0);
int maxReturn = 0;
for (int i = 1; i < prices.size(); ++i) {
// sell
sell.push_back(max(sell[i - 1], cool[i - 1]));
maxReturn = sell.back() > maxReturn ? sell.back() : maxReturn;
// buy
buy.push_back(max(sell[i - 1] - prices[i], buy[i - 1]));
// maxReturn = buy.back() > maxReturn ? buy.back() : maxReturn; (最大值不可能为此种状态,故可注释掉)
// cool
cool.push_back(buy[i - 1] + prices[i]);
maxReturn = cool.back() > maxReturn ? cool.back() : maxReturn;
}
return maxReturn;
}
};