【问题标题】:Best Time to Buy and Sell Stocks with the constraint of at most two transactions限制最多两笔交易的最佳买卖股票时间
【发布时间】:2019-03-12 13:59:55
【问题描述】:

从本网站提出的问题: https://www.interviewbit.com/problems/best-time-to-buy-and-sell-stocks-iii/

假设您有一个数组,其中第 i 个元素是给定股票在第 i 天的价格。

设计一个算法来找到最大的利润。您最多可以完成两笔交易。

注意: 您不能同时进行多笔交易(即,您必须先卖出股票,然后再购买)。

我的解决方案

int Solution::maxProfit(const vector<int> &A) {
    int i = 0, sz = A.size();
    int buy_price, sell_price;

    int profit, max_profit1 = 0, max_profit2 = 0;

    while(i<sz){
        while(i<sz-1 && A[i+1] < A[i]) ++i;
        buy_price = A[i];
        while(i<sz-1 && A[i+1] > A[i]) ++i;
        sell_price = A[i];
        profit = sell_price-buy_price;

        if(profit > max_profit2) {
            swap(max_profit1, max_profit2);
            max_profit2 = profit;
        }
        else if(profit > max_profit1) max_profit1 = profit;

        ++i;
    }

    return max_profit1 + max_profit2;
}

我的想法是跟踪所有利润(我以局部最小值买入并以局部最大值卖出);并拿起前两个。我跟踪变量 max_profit1 和 max_profit2 中的 2 个最大利润,其中 max_profit1

我对各种情况进行了尝试并得到了所需的答案,但我在 OJ 上提交的内容不正确。请帮助我指出该方法中的缺陷-希望在这种情况下避免使用 DP。提前致谢!

【问题讨论】:

    标签: algorithm


    【解决方案1】:

    局部最小值和最大值可能不是最优的,因为我们有 2 个交易可用。

    您的代码有时会使用错误的局部最小值/最大值

    例如给定输入:

    1 1 3 1 3 2 4

    您的解决方案给出:4

    正确答案是:5

    【讨论】:

    • 但是根据问题说明,卖之前不能再买。在您的示例中,我们在卖出前买入。我说的对吗?
    • @UtkarshGupta 是的,你是对的,对不起,我误解了这个问题,我会更新我的答案
    【解决方案2】:

    为什么要避免动态编程?

    如果我们向后迭代,我们就知道每次可能买入的最佳卖出价——这是迄今为止看到的最高价。我们还可以记录和更新从我们所在位置到结束的最佳交易。

    如果我们向前迭代,我们就知道每次可能卖出的最佳买入 - 这是迄今为止看到的最小值。我们还可以记录和更新从我们所在位置到开始的最佳交易。 而且我们可以通过将我们的位置与我们已经记录的从索引i + 1 到最后的最佳购买交易配对来更新整体解决方案。

    【讨论】:

      【解决方案3】:

      以下输入将失败: [1,2,4,2,5,7,2,4,9,0]

      在这种情况下,答案应该是 13。(第 1 天买入,第 6 天卖出,第 7 天买入,第 9 天卖出)。

      但根据代码,它返回 12。

      【讨论】:

      • 我不确定这是作为实际答案还是作为评论或问题正文中应该包含的更多信息。
      • 我后来意识到这个输入会失败;这反过来又让我意识到我最初的方法对于这个问题以及为什么应该使用 dp 会失败。
      【解决方案4】:

      你可以试试这个:

      public int maxProfit(int[] prices) {
          int sell1 = 0, sell2 = 0;
          int buy1 = Integer.MIN_VALUE, buy2 = Integer.MIN_VALUE;
      
          for(int i = 0; i < prices.length; i++) {
              buy1 = Math.max(buy1, -prices[i]);
              sell1 = Math.max(sell1, buy1 + prices[i]);
              buy2 = Math.max(buy2, sell1 - prices[i]);
              sell2 = Math.max(sell2, buy2 + prices[i]);
          }
          return sell2; 
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-07
        • 1970-01-01
        • 2020-10-04
        • 2018-03-20
        • 2021-11-29
        • 2017-09-26
        • 1970-01-01
        • 2021-10-06
        相关资源
        最近更新 更多