123. Best Time to Buy and Sell Stock III ~~

Posted CodesKiller

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了123. 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).

这道题要求我们只做两笔最大的交易,不同于I和II,一个要做一笔交易,一个要做无限多的交易。这道题开始不是很会做,想着把数组分成两段,然后每段里面求一笔最大交易,后来发现并不可行。于是看了大神的做法,代码如下:

public class Solution {

    public int maxProfit(int[] prices) {

        int lowestprice1 = Integer.MAX_VALUE;

        int lowestprice2 = Integer.MAX_VALUE;

        int profit1 = 0;

        int profit2 = 0;

        for(int p:prices){

            profit2 = Math.max(profit2,p-lowestprice2);

            lowestprice2 = Math.min(lowestprice2,p-profit1);

            profit1 = Math.max(profit1,p-lowestprice1);

            lowestprice1 = Math.min(lowestprice1,p);

        }

        return profit2;

    }

}

方法如下:

 

we can see that lowestBuyPrice1 is always the lowest price in the input array, maxProfit1 keeps track of the biggest difference between prices and lowest price so far, value change of lowestBuyPrice2 reflects the local valley in the input prices array and variable maxProfit2 maintains the maximum profit until the current price.

lowestBuyPrice1 and maxProfit1 are easy to understand. But how does lowestBuyPrice2 and maxProfit2 works? First, we shall see that lowestBuyPrice2 decreases whenever we hit a local minimum price. It indirectly (since it is negative) reflects the lowest price that is closest to the current price. When the current price is bigger than -lowestBuyPrice2, maxProfit2i = price i - (price (i-1) -maxProfit1 (i-1))= price i - price (i-1) +maxProfit1 (i-1), which means the accrued maximum profit until now.

以上是关于123. Best Time to Buy and Sell Stock III ~~的主要内容,如果未能解决你的问题,请参考以下文章

123. Best Time to Buy and Sell Stock III

123. Best Time to Buy and Sell Stock III

123. Best Time to Buy and Sell Stock III

123. Best Time to Buy and Sell Stock III ~~

leetcode-123. Best Time to Buy and Sell Stock III

[leetcode-123-Best Time to Buy and Sell Stock III]