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).
Algorithm Analysis:
Use the general algorithm "best time to Buy and Sell Stock IV" to change K to 2 OK
AC Code:
<span style= "Font-family:microsoft yahei;font-size:12px;" >public class solution{public int maxprofit (int[] prices) {return maxprofit (2,prices); } public int Maxprofit (int k, int[] prices) {if (Prices==null | | prices.length==0) return 0; if (K>prices.length)//k Times is greater than the number of days, the problem is converted to the "best time to Buy and Sell Stock II"-The infinite trade scenario {if (prices==nu ll) return 0; int res=0; for (int i=0;i<prices.length-1;i++) {int degit=prices[i+1]-prices[i]; if (degit>0) res+=degit; } return res; }/* Definition of maintenance: GLOBAL[I][J]: Maximum profit for j transactions can be made on the arrival of the first day. This is the global best local[i][j]: The maximum profit to be made on the last day of the last sale of a J-transaction at the time of arrival. This is the local optimal definition of recursion: Global[i][j]=max (Global[i-1][j],local[i][j]), that is, the first day no transaction, and the day I have a transaction Local[i][j]=max (global[i-1][j-1 ]+max (diff,0), Local[i-1][j]+diff) diff=price[i]-price[i-1]; */ Int[][] Global=new int[prices.length][k+1]; Int[][] Local=new int[prices.length][k+1]; for (int i=0;i<prices.length-1;i++) {int diff=prices[i+1]-prices[i]; for (int j=0;j<=k-1;j++) {Local[i+1][j+1]=math.max (Global[i][j]+math.max (diff,0), local[i][j+1 ]+diff); Global[i+1][j+1]=math.max (global[i][j+1],local[i+1][j+1]); }} return global[prices.length-1][k]; }}</span>
[Leetcode] [Java] best time to Buy and Sell Stock III