[Leetcode] 123. best time to Buy and Sell Stock III Java

Source: Internet
Author: User
Tags diff

Topic:

Say you has an array for which the i-th element is the price of a given-stock on day I.

Design an algorithm to find the maximum profit. You are in most of the transactions.

Note:
Engage in multiple transactions on the same time (ie, you must sell the stock before you buy again).

test instructions and analysis: give an array, representing the price of a stock in a certain day, to obtain the maximum profit. You can trade up to two times and cannot hold two shares at the same time.

method One: because you cannot hold two shares at the same time, you must buy and sell a trade, and then buy and sell a trade. This can be divided into two parts of the array, respectively, the maximum profit of the front and the next part of the maximum profit, add up is the current maximum profit, so there are n possible, the final traversal to get the maximum profit, because the beginning of the double loop, so the time complexity of 0 (n^2), commit timeout. Here you can use two scans to avoid double loops, so time complexity is reduced to O (n)

Code:

 Public classSolution { Public intMaxprofit (int[] prices) {        if(Prices = =NULL|| prices.length==0 | | Prices.length ==1)return0; int[] Leftprofit =New int[Prices.length]; intMinprice = Prices[0]; intMaxprofit = 0;  for(inti=1;i<prices.length;i++) {//Find the maximum profit that can be obtained from the front and back, the maximum profit for the current price minus the previous minimum price and the previous maximum profit of the larger valueMaxprofit = Math.max (maxprofit,prices[i]-minprice); Minprice=math.min (Minprice,prices[i]); Leftprofit[i]=Maxprofit; }        int[] Rightprofit =New int[Prices.length]; intMaxprice = prices[prices.length-1]; Maxprofit= 0;  for(inti=prices.length-2;i>=0;i--) {//from the back forward to find the I point can get the maximum profit, the maximum profit for the current maximum price minus the current price and a maximum profit between the large valueMaxprofit = Math.max (maxprofit,maxprice-Prices[i]); Maxprice=Math.max (Maxprice,prices[i]); Rightprofit[i]=Maxprofit; } Maxprofit= 0;  for(inti=0;i<prices.length;i++) {Maxprofit= Math.max (maxprofit,leftprofit[i]+Rightprofit[i]); }        returnMaxprofit; }}

Method Two:

The core of the second solution is to assume that at the beginning of the hand is only 0 yuan, then if the price of the stock to buy prices, the money on hand need to subtract this price, if the prices of the sale of the stock to the cost of the money need to add this.

It defines 4 states:

Buy1[i] means the maximum amount of money left before I make the first trade after buying the stock;

Sell1[i] means that the most money left after the first trade is sold in the prior I day;

Buy2[i] means the most money left before I make a second deal to buy shares;

Sell2[i] means that the most money left after the second deal is sold in the first I day;

Then Sell2[i]=max{sell2[i-1],buy2[i-1]+prices[i]}

Buy2[i]=max{buy2[i-1],sell[i-1]-prices[i]}

Sell1[i]=max{sell[i-1],buy1[i-1]+prices[i]}

Buy1[i]=max{buy[i-1],-prices[i]}

You can see that the above four states are only related to the previous state, so you can use variables to store them instead of using arrays.

Code:

classSolution { Public intMaxprofit (int[] prices) {        if(Prices = =NULL|| Prices.length < 2)            return0; //Four variables representing the profit after the current operation        intFirstBuy = integer.min_value, Firstsell = 0; intSecondbuy = integer.min_value, Secondsell = 0;  for(intcurprice:prices) {FirstBuy= Math.max (FirstBuy,-Curprice); Firstsell= Math.max (Firstsell, Curprice +firstbuy); Secondbuy= Math.max (Secondbuy, Firstsell-Curprice); Secondsell= Math.max (Secondsell, Secondbuy +Curprice); }        returnSecondsell; }}

Method Three: quoted from: http://blog.csdn.net/linhuanmars/article/details/23236995

Here we first explain the maximum number of possible K-trading algorithms, and then up to two times we just need to take K to 2. We still use "local optimal and global optimal solution". We maintain two kinds of quantities, one is the current arrival on the first day can be a maximum of J transactions, the best profit is how much (Global[i][j]), the other is the current arrival of the first day, up to J-trade, and the last trade on the day to sell the best profit is how much (Local[i][j]). Let's look at the recursive, the global is relatively simple,

Global[i][j]=max (Local[i][j],global[i-1][j]),

That is to go to the current part of the best, and the best in the past the largest of the big one (because the last deal if the current day must be in the local best inside, otherwise must be in the past global optimal inside). For the maintenance of local variables, the recursive type is

Local[i][j]=max (Global[i-1][j-1]+max (diff,0), Local[i-1][j]+diff),

That is, look at two, the first is the global to I-1 day j-1 transactions, and then add today's deal, if today is to make money (that is, as long as the j-1 transaction, the last time to take the current day), the second is to take the local i-1 days J transactions, Then add today's difference (here because local[i-1][j], for example, contains the sale of I-1 day, so now becomes the day I sell, does not increase the number of trades, and here whether the diff is greater than 0 must be added, because otherwise will not meet LOCAL[I][J] Conditions that must be sold on the last day).
The above algorithm for the number of days need a scan, and each time to the number of transactions to be recursive solution, so the time complexity is O (n*k), if the maximum of two transactions, then the complexity of O (n). Space only need to maintain the day data can be, so is O (k), when k=2, then is O (1). The code is as follows:

 Public intMaxprofit (int[] prices) {    if(prices==NULL|| Prices.length==0)        return0; int[] Local =New int[3]; int[] Global =New int[3];  for(inti=0;i<prices.length-1;i++)    {        intdiff = prices[i+1]-Prices[i];  for(intj=2;j>=1;j--) {Local[j]= Math.max (global[j-1]+ (diff>0?diff:0), local[j]+diff); GLOBAL[J]=Math.max (Local[j],global[j]); }    }    returnGlobal[2];}

[Leetcode] 123. best time to Buy and Sell Stock III Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.