码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-01-31 10:36:08      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:cal   dir   tip   return   which   ret   ica   ack   ons   

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 ~~

标签:cal   dir   tip   return   which   ret   ica   ack   ons   

原文地址:http://www.cnblogs.com/codeskiller/p/6358634.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!