122. 买卖股票的最佳时机 II - 力扣(LeetCode)
//由于当天买可以当天卖 == >> 每天都更新状态
//状态一: 当前卖亏本 == >> 穿越到昨天卖出 然后买今天(即理解为昨天买了昨天就卖)
//状态二: 当前卖盈利 == >> 卖出 == >> 更新答案
//状态三: 当前卖亏本但是卖出前些天的盈利 == >> 穿越到昨天不卖出,今天卖出 == >> 更新答案
class Solution {
public:
int maxProfit(vector<int>& prices)
{
int ans = 0;
int pre = INT_MAX;
int sell = pre;
int profit = 0;
for(auto x : prices)
{
if(x > pre)
{//可以出售
ans += x - pre;
profit = x - pre;
pre = sell = x;
}
else
{//出售亏本
if(x - sell > profit)
{
ans = ans - profit + x - sell;
profit = x - sell;
}
else
{
pre = x;
}
}
}
return ans;
}
};