best time to Buy and Sell Stock III

Source: Internet
Author: User

https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/

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).

Problem Solving Ideas:

First think, according to the best time to Buy and Sell the stock problem solution, find a maximum interval, and then find the second large interval, this second large interval must not coincide with the first large interval, so there is a variable buyday to record, in addition to a number of several variables. However, this method is wrong. Why? Because for the problem that can buy and sell two times, best time to buy and Sell the biggest range of the stock problem, here, sometimes it is better to separate to calculate. Think of, for example, 6,1,3,2,4,7. The maximum interval for problem one is 1-7=6. If it is separated two times, 1-3+2-7=7. So the following code is wrong, and it's not easy to understand.

 Public classSolution { Public intMaxprofit (int[] prices) {        intMaxprofit = 0; intSecondmaxprofit = 0; intProfit = 0; intThistimemaxprofit = 0; intBuyday = 0; intMaxbuyday = 0; intBuyvalue; if(Prices.length = = 0){            return0; }Else{Buyvalue= Prices[0]; Buyday= 0; }                 for(inti = 0; i < prices.length; i + +) {Profit= Prices[i]-Buyvalue; if(Profit >Maxprofit) {Maxprofit=profit; Maxbuyday=Buyday; }            //update the maximum value of a single buy day, that is, local, not the maximum profit for global            if(Profit >Thistimemaxprofit) {Thistimemaxprofit=profit; }                        //There is a new minimum purchase price, both to look at the maximum profit in this local interval, that is, Thistimemaxprofit, is not the second largest profit//so also to determine whether to buy the day is not and the maximum profit for the day, to prevent duplication            if(Prices[i] <buyvalue) {                if(Thistimemaxprofit > Secondmaxprofit && thistimemaxprofit <= maxprofit && buyday! =maxbuyday) {Secondmaxprofit=Thistimemaxprofit; } buyvalue=Prices[i]; Buyday=i; Profit= 0; Thistimemaxprofit= 0; }            //on the last day, if the price has been up, not to touch a new buy point, but also to update the second largest profit            if(i = = Prices.length-1 && Buyday! =maxbuyday) {                if(Thistimemaxprofit > Secondmaxprofit && thistimemaxprofit <=Maxprofit) {Secondmaxprofit=Thistimemaxprofit; }            }        }        returnMaxprofit +Secondmaxprofit; }}

So the following solution has appeared. Because two transactions will not coincide, must be divided into the K-day around. So traversing the entire interval, to the daily as a division, to find out the left and right two intervals of the maximum profit, and then add this pair of profits, to find the largest total profit. However, the time complexity of this code must be O (n^2), timed out.

 Public classSolution { Public intMaxprofit (int[] prices) {        intMaxprofit = 0; intProfit = 0; intBuyvalue; intLeftmaxprofit = 0; intRightmaxprofit = 0; if(Prices.length = = 0){            return0; }Else{Buyvalue= Prices[0]; }                 for(inti = 0; i < prices.length; i + +) {Profit= Prices[i]-Buyvalue; if(Profit >Maxprofit) {Maxprofit=profit; }                        if(Prices[i] <buyvalue) {Buyvalue=Prices[i]; Profit= 0; }        }                 for(inti = 0; i < prices.length; i + +) {Buyvalue= Prices[0];  for(intj = 0; J < I; J + +) {Profit= Prices[j]-Buyvalue; if(Profit >Leftmaxprofit) {Leftmaxprofit=profit; }                            if(Prices[i] <buyvalue) {Buyvalue=Prices[j]; Profit= 0; }} Buyvalue=Prices[i];  for(intK = i; K < Prices.length; k++) {Profit= Prices[k]-Buyvalue; if(Profit >Rightmaxprofit) {Rightmaxprofit=profit; }                            if(Prices[i] <buyvalue) {Buyvalue=Prices[k]; Profit= 0; }            }            if(Leftmaxprofit + rightmaxprofit >Maxprofit) {Maxprofit= Leftmaxprofit +Rightmaxprofit; }        }        returnMaxprofit; }}

We had to use space for time , separate execution two traversal, but with two arrays, respectively recorded from left and right to start the maximum profit, and finally add the two, and then iterate to find out the total profit maximum.

 Public classSolution { Public intMaxprofit (int[] prices) {        intProfit = 0; intBuyvalue; intSellvalue; int[] Leftmaxprofit =New int[Prices.length]; int[] Rightmaxprofit =New int[Prices.length]; int[] Maxprofit =New int[Prices.length]; intMaxprofitall = 0; if(Prices.length = = 0){            return0; }Else{Buyvalue= Prices[0]; }                 for(inti = 1; i < prices.length; i++){            //It is important to note that the equation of state transformation in DP is not writable as leftmaxprofit[i] = prices[i]-Buyvalue//consider that the maximum profit margin has been over, and the profit is starting to fall, but the local maximum profit in that interval is still the largest value in the front.//so to leftmaxprofit[i-1] and the current value to take the maximumLeftmaxprofit[i] = Math.max (Leftmaxprofit[i-1], prices[i]-buyvalue); if(Prices[i] <buyvalue) {Buyvalue=Prices[i]; }        }                if(Prices.length = = 0){            return0; }Else{Sellvalue= Prices[prices.length-1]; }                 for(inti = prices.length-2; I >= 0; i--) {Rightmaxprofit[i]= Math.max (rightmaxprofit[i + 1], Sellvalue-Prices[i]); if(Prices[i] >sellvalue) {Sellvalue=Prices[i]; }        }                 for(inti = 0; i < prices.length; i++) {Maxprofit[i]= Leftmaxprofit[i] +Rightmaxprofit[i]; }         for(inti = 0; i < prices.length; i++) {Maxprofitall=Math.max (Maxprofitall, maxprofit[i]); }                returnMaxprofitall; }}

Summarize:

From left to right dp[i+1] = Max{dp[i], prices[i+1]-minprices}, Minprices is the lowest price in the interval [0,1,2...,i]

From right to left dp[i-1] = Max{dp[i], maxprices-prices[i-1]}, Maxprices is the highest price in the interval [i,i+1,..., n-1].

best time to Buy and Sell Stock III

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.