Question:
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).
Analysis:
Problem Description: Gives an array of integers, where the I element represents the stock price of day I.
Design a program to find the maximum profit, up to two trades.
Idea one: The method of solving violence. A cycle is divided into two segments, each seeking the maximum profit, and then finding the maximum profit, time complexity O (n2).
Idea two: The Dynamic programming thought. The first step is to iterate over and calculate the profit that is available for the current transaction, and then traverse it backwards (the forward traversal is not the same as the reverse traversal requirement, and the positive direction is the profit that can be obtained if the transaction is currently in progress, while the reverse traversal requires the maximum benefit from I to the last).
Answer:
Public classSolution { Public Static intMaxprofit (int[] prices) { if(Prices.length = = 0 | | prices.length = = 1) return0; intn =prices.length; //looking for the maximum profit intLow = Prices[0]; intprofit0 = 0; int[] Pro =New int[n]; pro[0] = 0; for(intI=1; i<n; i++) { if(Prices[i] <Low ) Low=Prices[i]; inttemp = prices[i]-Low ; if(Profit0 <temp) profit0=temp; Pro[i]=temp; } //reverse the search for maximum profit intHigh = Prices[prices.length-1]; intprofit1 = 0; int[] Pro1 =New int[n]; Pro1[n-1] = 0; for(intI=n-2; i>=0; i--) { if(High <Prices[i]) high=Prices[i]; inttemp = high-Prices[i]; if(Profit1 <temp) profit1=temp; Pro1[i]=profit1; } intres = 0; for(inti=0; i<n; i++) { inttemp = Pro[i] +Pro1[i]; //System.out.println ("Pro:" +pro[i]+ "Pro1:" +pro1[i]); if(Res <temp) Res=temp; } returnRes; } }
Leetcode--best time to Buy and Sell Stock III