[Leetcode-java] best time to Buy and Sell Stock IV

Source: Internet
Author: User

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. Transactions at the most K.

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

Test instructions: Given an array that represents the price of the stock each day, given the number k, requires the maximum number of trades to be k, to seek the greatest benefit.

Idea: Based on the idea of best time to Buy and Sell Stock III, create a dynamic programming array,

LOCAL[I][J]: The first day of arrival, on the first day of the completion of the last transaction, a total of trading J times the best interest.

GLOBAL[I][J]: For the first day of arrival, the total transaction of the maximum benefit of J.

The following recursive formula is known by definition:

For the lcoal array, local[i][j] in Local[i-1][j] time has completed the J-trade, so from the i-1 day to the day I, regardless of the difference is how much, should be added, while the comparison should be global[i-1][j-1], I-1 days to complete the j-1 transactions, the first day if the difference is greater than 0 to make money, plus, do not make money plus 0, that is, the recurrence formula is: local[i][j] = Math.max (local[i-1][j] + diff, Global[i-1][j-1] + (diff > 0? diff:0));

For the global array it is relatively simple: global[i][j] = Math.max (Local[i][j], global[i-1][j]);

Here is the code I wrote for the first time:

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

At this time, when the K value is very large, if the prices array is not very large, the effect will be very poor, so start to increase the judgment of K, if greater than the length of the prices array, the title can be understood as in these days, unlimited number of transactions, the greatest benefit, then simply change to the following code:

 Public classSolution { Public intMaxprofit (intKint[] prices) {        if(Prices = =NULL|| Prices.length < 2)            return0; //Increased Judgment        if(k >= Prices.length)returnSolvemaxprofit (prices); int[] Local =New int[Prices.length] [K+1]; int[] Global =New int[Prices.length] [K+1];  for(inti = 1; i < prices.length; i++){            intdiff = prices[i]-prices[i-1];  for(intj = 1; J <= K; J + +) {Local[i][j]= Math.max (Local[i-1][j] + diff, Global[i-1][j-1] + (diff > 0? diff:0)); GLOBAL[I][J]= Math.max (Local[i][j], global[i-1][j]); }        }                returnGlobal[prices.length-1][k]; }    //Increased Judgment     Public int Solvemaxprofit(int[] prices) {        intres = 0;  for(inti = 1; i < prices.length; ++i) {if(Prices[i]-prices[i-1] > 0) {res+ = Prices[i]-prices[i-1]; }        }        returnRes; }}

Finally refer to the other people's optimization code, their own code in the dynamic planning of the time is more rigid, wasted a lot of useless space, their own observation of two arrays in comparison, all only need to compare their own above a value, so can speak two-dimensional array simplified to one-dimensional, at the same time, in the calculation, In order not to overwrite the previous content, if the next loop of J from 1 to K-1 will take advantage of the result of the previous loop instead of the upper level in the two-bit array, J should take the value in flashbacks, and the simplified AC code is as follows:

 Public classSolution { Public intMaxprofit (intKint[] prices) {        if(Prices = =NULL|| Prices.length < 2)            return0; if(k >= Prices.length)returnSolvemaxprofit (prices); int[] Local =New int[K+1];//The maximum benefit of selling J times on the first day        int[] Global =New int[K+1];//J-time maximum benefitLocal[0] = 0; global[0] = 0;  for(inti = 1; i < prices.length; i++){            intdiff = prices[i]-prices[i-1];  for(intj = k; J >= 1; --J) {//ReverseLOCAL[J] = Math.max (Global[j-1] + (diff > 0? diff:0), Local[j] +diff); GLOBAL[J]=Math.max (Local[j], global[j]); }        }                returnGlobal[k]; }         Public intSolvemaxprofit (int[] prices) {        intres = 0;  for(inti = 1; i < prices.length; ++i) {if(Prices[i]-prices[i-1] > 0) {res+ = Prices[i]-prices[i-1]; }        }        returnRes; }}

Reference Link: http://blog.csdn.net/linhuanmars/article/details/23236995

[Leetcode-java] best time to Buy and Sell Stock IV

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.