Title
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
given an array of prices, Prices[i] represents the stock price of day I. The subject is only able to buy and sell up to two times and ask what the maximum benefit is.
Ideas
Calculate the maximum profit of MAXPROFIT1 and the maximum profit maxProfit2 of 2 times, then the maximum value.
The solution for buying and selling is already available, see best time to Buy and Sell Stock.
We need to determine where the turning point is if we buy or sell two times. That is, on the first day of sale, buy in I+1 day. In order to get the maximum value we need to know what is the maximum profit I have sold on the first day, and what is the maximum income I buy on i+1 day. The maximum profit for a daily sale the best time to Buy and Sell the stock has given the solution, only need to One-pass is complete. So how do you calculate the maximum benefit you can get from buying a day? The same, just a change of direction.
For this we maintain two arrays of buyprofit, Sellprofit, Sellprofit[i] that sell in the first day to get the maximum benefit. Buyprofit[i] indicates that the maximum revenue will be obtained by buying on the first day. The maximum yield of two transactions Maxprofit2=max (buyprofit[i]+sellprofit[i+1]) i=1,2,3,.... n-3, where n is the length of the prices array.
Code
Class Solution {Public:int Maxprofit (vector<int> &prices) {int size=prices.size (); if (size<=1) return 0; Int*back=new Int[size]; Int*front=new Int[size]; int maxprofit=0; int minprice=prices[0]; int maxprice=prices[size-1];back[size-1]=front[0]=0; Find out that the first half of the interval ending with I can get the maximum profit maxprofit=0. for (int i=1; i<size; i++) {int profit=prices[i]-minprice;if (profit>maxprofit) Maxprofit=profit; Front[i]=maxprofit; if (Prices[i]<minprice) minprice=prices[i]; }//Find out the most profitable maxprofit=0 to buy and sell once in the second half of the period of I start; for (int i=size-2; i>=0; i--) {int profit=maxprice-prices[i];if (profit>maxprofit) Maxprofit=profit; Back[i]= Maxprofit; if (Prices[i]>maxprice) maxprice=prices[i]; }//ask for the maximum value of two transactions maxprofit=0; for (int i=0; i<size; i++) {if (i==size-1) {if (front[i]>maxprofit) maxprofit=front[i];} Else{if (front[i]+back[i+1]>maxprofit) maxprofit=front[i]+back[i+1];} } return maxprofit; }};
Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.
Leetcode:best time to Buy and Sell Stock III [123]