目录
121. 买卖股票的最佳时机
123. 买卖股票的最佳时机 III
188. 买卖股票的最佳时机 IV
309. 买卖股票的最佳时机含冷冻期
如果某一天出售股票可以得到最大利润,那么股票买入的价格一定是这天之前股票的最低价格。
所以我们可以在遍历股票价格的时候不断更新股票的最低价格,然后尝试在今天卖出,不断取能够卖出的最大利润。
class Solution {
public:
int maxProfit(vector& prices) {
int ans=0,minval=INT_MAX;
for(int i=0;i
每只股票一共有五种状态:
0.未曾持过股
1.第一次持股
2.第一次卖出
3.第二次持股
4.第二次卖出
class Solution {
public:
int maxProfit(vector& prices) {
if (prices.size() == 0) return 0;
vector dp(5, 0);
dp[1] = -prices[0];
dp[3] = -prices[0];
for (int i = 1; i < prices.size(); i++) {
dp[1] = max(dp[1], dp[0] - prices[i]);
dp[2] = max(dp[2], dp[1] + prices[i]);
dp[3] = max(dp[3], dp[2] - prices[i]);
dp[4] = max(dp[4], dp[3] + prices[i]);
}
return dp[4];
}
};
与上一题类似,索引为奇数时表示持有股票,索引为偶数是表示不持有股票
class Solution {
public:
int maxProfit(int k, vector& prices) {
if (prices.size() == 0) return 0;
vector dp(2*k+1, 0);
for(int i=1;i
每支股票的状态:
1.持有股票
2.未持有股票
一共有四种状态
class Solution {
public:
int maxProfit(vector& prices) {
vector> dp(prices.size(),vector(4,0));
dp[0][0]=-prices[0];
for(int i=1;i