LeetCode --Best Time to Buy and Sell Stock III

股票买卖最佳时机III
本文介绍了一种解决LeetCode上“最佳买卖股票时机III”问题的算法。该问题要求找到给定股价数组中的最大利润,允许最多进行两次交易。文章详细解析了状态机算法,并通过动态规划方法给出了具体实现。

LeetCode –Best Time to Buy and Sell Stock III

技术与社会生态的相互作用,使得技术发展经常带来更深远的问题,远远超出了技术设备的直接目的和运作本身,同样的技术,引入不同的环境,或在不同条件下,会带来非常不同的结果


题目描述

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

至多交易2次,求最大利益。

算法解释

  1. basically we want to maximize the formula: -price1 + price2 - price3 + price4, where every price appear in that order. So every time we visit a new price, we update the max possible value of 4 (partial) formula. That’s why we use max for each of the 4 states.
    也就是状态机4个状态。和cooldown相似。

在每个步骤中,我们可以看到,oneBuy始终是输入数组中的最低价格,oneBuyOneSell跟踪价格和最低价格之间的最大差异,TwoBuy的价值变化反映了输入价格数组中的谷底。
变量TwoBuyTwoSell保持直到目前的价格的最大的利润,
(代码比较清晰易懂,请看代码)

  1. DP

f[k, ii] represents the max profit up until prices[ii] (Note: NOT ending with prices[ii]) using at most k transactions.


f[k, ii] = max(f[k, ii-1], prices[ii] - prices[jj] + f[k-1, jj]) { jj in range of [0, ii-1] }
= max(f[k, ii-1], prices[ii] + max(f[k-1, jj] - prices[jj]))

      f[0, ii] = 0; 0 times transation makes 0 profit
      f[k, 0] = 0; if there is only one price data point you can't make any money no matter how many times you can trade

状态转移方程明了了,解释略

代码

public int maxProfit(int[] prices) {
    int oneBuy = Integer.MIN_VALUE;
    int oneBuyOneSell = 0;
    int twoBuy = Integer.MIN_VALUE;
    int twoBuyTwoSell = 0;
    for(int i = 0; i < prices.length; i++){
        oneBuy = Math.max(oneBuy, -prices[i]);//we set prices to negative, so the calculation of profit will be convenient
        oneBuyOneSell = Math.max(oneBuyOneSell, prices[i] + oneBuy);
        twoBuy = Math.max(twoBuy, oneBuyOneSell - prices[i]);//we can buy the second only after first is sold
        twoBuyTwoSell = Math.max(twoBuyTwoSell, twoBuy + prices[i]);
    }

    return Math.max(oneBuyOneSell, twoBuyTwoSell);
}

使用DP的方法

class Solution {
public:
    int maxProfit(vector<int> &prices) {

        if (prices.size() <= 1) return 0;
        else {
            int K = 2; // number of max transation allowed
            int maxProf = 0;
            vector<vector<int>> f(K+1, vector<int>(prices.size(), 0));
            for (int kk = 1; kk <= K; kk++) {
                int tmpMax = f[kk-1][0] - prices[0];
                for (int ii = 1; ii < prices.size(); ii++) {
                    f[kk][ii] = max(f[kk][ii-1], prices[ii] + tmpMax);
                    tmpMax = max(tmpMax, f[kk-1][ii] - prices[ii]);
                    maxProf = max(f[kk][ii], maxProf);
                }
            }
            return maxProf;
        }
    }
};
这段代码是解决 **LeetCode 121. Best Time to Buy and Sell Stock** 的经典贪心算法解法。它的目标是找出**只进行一次买卖**的情况下,可以获得的最大利润。 --- ## 🧠 问题描述(LeetCode 121) 给定一个数组 `prices`,其中 `prices[i]` 表示某支股票第 `i` 天的价格。 你只能选择 **某一天买入** 并在 **未来某一天卖出**(不能当天买卖),计算你能获得的 **最大利润**。 --- ## ✅ 示例 ```cpp 输入: prices = [7,1,5,3,6,4] 输出: 5 解释: 第 2 天买入(价格 = 1),第 5 天卖出(价格 = 6),利润为 6 - 1 = 5。 ``` --- ## 🧩 代码详解 ```cpp class Solution { public: int maxProfit(vector<int>& prices) { int ans = 0; // 用于记录最大利润 int min_price = prices[0]; // 用于记录当前遇到的最小买入价格 for (int p : prices) { ans = max(ans, p - min_price); // 计算当前利润,更新最大利润 min_price = min(min_price, p); // 更新最小买入价格 } return ans; } }; ``` --- ## 📌 逐行解释 ### 1. 初始化 ```cpp int ans = 0; int min_price = prices[0]; ``` - `ans` 是最终要返回的最大利润,初始化为 0。 - `min_price` 表示当前为止最小的买入价格,初始化为第一天的价格。 ### 2. 遍历价格数组 ```cpp for (int p : prices) { ``` - 使用范围 for 遍历每一天的价格 `p`。 ### 3. 计算当前利润并更新最大利润 ```cpp ans = max(ans, p - min_price); ``` - 如果当前价格 `p` 减去 `min_price`(之前最低价)大于当前最大利润 `ans`,则更新 `ans`。 ### 4. 更新最小买入价格 ```cpp min_price = min(min_price, p); ``` - 每次遍历都要更新 `min_price`,确保我们始终用最低价买入。 --- ## 🧪 执行过程示例 以 `prices = [7,1,5,3,6,4]` 为例: | i | price | min_price | profit (price - min_price) | ans | |---|-------|-----------|-----------------------------|-----| | 0 | 7 | 7 | 0 | 0 | | 1 | 1 | 1 | 0 | 0 | | 2 | 5 | 1 | 4 | 4 | | 3 | 3 | 1 | 2 | 4 | | 4 | 6 | 1 | 5 | 5 | | 5 | 4 | 1 | 3 | 5 | 最终返回 `ans = 5`。 --- ## ⏱️ 时间与空间复杂度 - **时间复杂度**:O(n),只遍历一次价格数组。 - **空间复杂度**:O(1),只使用了几个变量。 --- ## ✅ 与其他解法对比 | 方法 | 时间复杂度 | 空间复杂度 | 是否推荐 | |------|------------|------------|----------| | 暴力枚举(双重循环) | O(n²) | O(1) | ❌ 不推荐 | | 贪心算法(本解法) | O(n) | O(1) | ✅ 强烈推荐 | | 动态规划 | O(n) | O(n) | ✅ 可选 | --- ## 💡 拓展:动态规划版本(可选) ```cpp int maxProfit(vector<int>& prices) { int n = prices.size(); vector<int> dp(n, 0); // dp[i] 表示第 i 天为止的最大利润 int min_price = prices[0]; for (int i = 1; i < n; ++i) { dp[i] = max(dp[i - 1], prices[i] - min_price); min_price = min(min_price, prices[i]); } return dp[n - 1]; } ``` --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值