121. 买卖股票的最佳时机
class Solution {
public:
int maxProfit(vector<int>& prices) {
int max_profit=INT_MIN;
int history_min=prices[0];
for(int i=1; i<prices.size();i++){
int cur=prices[i]-history_min;
max_profit=max(max_profit,cur);
history_min=min(history_min,prices[i]);
}
return max_profit>0?max_profit:0;
}
};
遍历所有可能的卖出点,跟历史最低价格比,算当前利润,得到全局最优。历史低价要动态更新。
122. 买卖股票的最佳时机 II
class Solution {
public:
int maxProfit(vector<int>& prices) {
int sum=0,day_profit;
for(int i=1; i<prices.size(); i++){
day_profit=prices[i]-prices[i-1];
if(day_profit>0)
sum+=day_profit;
}
return sum;
}
};
利润是可以分解的,累计所有正盈利的单天,即为最大收益。
123. 买卖股票的最佳时机 III
class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.size() == 0) return 0;
vector<vector<int>> dp(prices.size(), vector<int>(5, 0));
dp[0][1] = -prices[0];
dp[0][3] = -prices[0];
for (int i = 1; i < prices.size(); i++) {
dp[i][0] = dp[i - 1][0];
dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
dp[i][2] = max(dp[i - 1][2], dp[i - 1][1] + prices[i]);
dp[i][3] = max(dp[i - 1][3], dp[i - 1][2] - prices[i]);
dp[i][4] = max(dp[i - 1][4], dp[i - 1][3] + prices[i]);
}
return dp[prices.size() - 1][4];
}
};
dp[i][j]表示第i天状态j所剩最大现金。j的具体定义:
0.没有操作
1.第一次持有股票
2.第一次不持有股票
3.第二次持有股票
4.第二次不持有股票
状态转移:
1.不操作,保留上一天同状态
2.操作,按以下顺序:0->1->2->3->4
1303

被折叠的 条评论
为什么被折叠?



