【leetcode】123. Best Time to Buy and Sell Stock III(c/c++,hard难度)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/maotianyi941005/article/details/81360507

原题链接

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 (i.e., you must sell the stock before you buy again).

Example 1:

Input: [3,3,5,0,0,3,1,4]
Output: 6
Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
             Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.

Example 2:

Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
             Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
             engaging multiple transactions at the same time. You must sell before buying again.

Example 3:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

题目在II的基础上限定了最多两笔交易,依旧是只能买一卖一。

我的代码

错误思路(❌): 本来想的是按之前II的low high标记每一段局部递增,然后计算局部利润,存最大的两个局部利润最后求和。但是这样用例只能通过189/200。举个不通过的例子 [1,2,4,2,5,7,2,4,9,0]

按之前的局部分段利润来说是【1,2,4】=3、【2,5,7】=5、【2,4,9】=7 取5+7=12

但是正确解法是【1,2,4,2,5,7】=6、【2,4,9】=7,6+7=13

这样II的解法就行不通了。

思路2(✅):参考《——

从前往后扫描,f[i] 记录前 i 天中买卖一次的最大收益(不一定在第 i 天卖)。

从后往前扫描,计算从i th天买入能获取的最大收益,即第i天后的最大价格 - prices[i]。

两次交易的最大收益sum = 第i天买入能获取的最大收益 + f[ i -1 ]

时间复杂度O(n)

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int sum = 0;
        int len = prices.size();
        if(len == 0) return 0; //空会触发 runtime error []
        vector<int> f(len,0);
        int i,low = prices[0],max_p = prices[len-1];
        for(i = 1;i < len; i++){
             if(prices[i] > prices[i-1]){ // increase
                f[i] = max(f[i-1],prices[i] - low);
              }else f[i] = f[i-1];
            if(prices[i] < low) low = prices[i];
         }
        for( i = len-1 ; i >0 ;i--){//buy in ith day and sell in max_p
             max_p = max(max_p,prices[i]);
             if((max_p - prices[i]) > 0){
                sum = max(sum, max_p - prices[i] + f[i-1]);
            }

        }
        if((max_p - prices[i]) > 0){
            sum = max(sum, max_p - prices[i]);
          }
        return sum;
    }
};

猜你喜欢

转载自blog.csdn.net/maotianyi941005/article/details/81360507