代码随想录算法训练营第五十一天|股票问题专题(3)

目录

LeeCode 309.最佳买卖股票时机含冷冻期

LeeCode 714.买卖股票的最佳时机含手续费

贪心算法

动态规划法


LeeCode 309.最佳买卖股票时机含冷冻期

309. 最佳买卖股票时机含冷冻期 - 力扣(LeetCode)

动归五部曲:

1.确定dp数组及下标含义: dp[i][j],第i天状态为j,所剩的最多现金。状态一:持有股票状态(今天买入股票,或之前买入股票后没有操作,一直持有);状态二:保持卖出股票的状态(已度过了冷冻期);状态三:今天卖出股票;状态四:冷冻状态;

2.确定递推公式:dp[i][0] = max(dp[i - 1][0], dp[i - 1][3] - prices[i], dp[i - 1][1] - prices[i]);  dp[i][1] = max(dp[i - 1][1], dp[i - 1][3]);   dp[i][2] = dp[i - 1][0] + prices[i];  dp[i][3] = dp[i - 1][2];

3.dp数组如何初始化:dp[0][0] = -prices[0]; dp[0][1] = 0; dp[0][2] = 0; dp[0][3] = 0;

4.确定遍历顺序:从前到后遍历;

5.举例递推dp数组;

代码

class Solution {
public:
    int maxProfit(vector<int>& prices) {
    	int n = prices.size();
    	if (n == 0) return 0;
    	vector<vector<int>> dp(n, vector<int>(4, 0));
    	dp[0][0] -= prices[0];
    	for (int i = 1; i < n; i ++) {
    		dp[i][0] = max(dp[i - 1][0], max(dp[i - 1][3] - prices[i], dp[i - 1][1] - prices[i]));
    		dp[i][1] = max(dp[i - 1][1], dp[i - 1][3]);
    		dp[i][2] = dp[i - 1][0] + prices[i];
    		dp[i][3] = dp[i - 1][2];
		}
        return max(dp[n - 1][3], max(dp[n - 1][1], dp[n - 1][2]));
    }
};

时间复杂度:O(n)                                          空间复杂度:O(n) 


LeeCode 714.买卖股票的最佳时机含手续费

714. 买卖股票的最佳时机含手续费 - 力扣(LeetCode)

贪心算法

代码:

class Solution {
public:
    int maxProfit(vector<int>& prices, int fee) {
    	int result = 0;
    	int minPrice = prices[0]; //记录最低价格
    	for (int i = 1; i < prices.size(); i++) {
            //买入
    		if (prices[i] < minPrice) minPrice = prices[i];
            //保持原有状态
    		if (prices[i] >= minPrice && prices[i] <= minPrice + fee) continue;
		    //计算利润
            if (prices[i] > minPrice + fee) {
			     result += prices[i] - minPrice - fee;
			     minPrice = prices[i] - fee; //避免重复扣手续费
		    }
		} 
	    return result;	
    }
};

 时间复杂度:O(n)                                          空间复杂度:O(1) 

动态规划法

思路:

与 122.买卖股票的最佳时机II 解题步骤基本一致,差别在于递推公式中需要考虑手续费问题。

递推公式:dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i] - fee);

代码

class Solution {
public:
    int maxProfit(vector<int>& prices, int fee) {
    	int n = prices.size();
    	vector<vector<int>> dp(n, vector<int>(2, 0));
    	dp[0][0] -= prices[0];
    	for (int i = 1; i < n; i++) {
    		dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] - prices[i]);
    		dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i] - fee);
		}
		return max(dp[n - 1][0], dp[n - 1][1]);
    }
};

时间复杂度:O(n)                                     空间复杂度:O(n) 

猜你喜欢

转载自blog.csdn.net/weixin_74976519/article/details/131145890