Leetcode (188) best time to buy and Sell stock IV (Java) __arrays

Source: Internet
Author: User
Tags diff
The topics are as follows:
best time to buy and Sell the total accepted:43912 total submissions:135635 My submissions question Solution
Say you have an array for which the ith element are the price of a given the
If you are were only permitted to complete in most one transaction (ie, buy one and sell one share of the "stock", design an AL Gorithm to find the maximum profit.


The analysis is as follows:

Feeling is a very difficult topic, will not do, comprehensive look at the online discussion.

The key to the problem is to write the following dynamic transfer equation:

Local[i][j]=max (Global[i-1][j-1]+max (diff,0), Local[i-1][j]+diff),

Global[i][j]=max (Local[i][j],global[i-1][j]),

And the concrete understanding of this equation is this.

First of all, global is simpler, but it is always compared with the calculated local, and the large is saved in global.

Then look at the local, the key is to understand the definition of the local, Local[i][j] said that the first day I conducted a J-transaction, and the first day of the first J transactions in the maximum profit, so local[i][j] There must be a transaction, that is, when the last transaction occurred in the first day. The local is completed by a comparison of two parts.

The first part is, Global[i-1][j-1]+max (diff,0), that is, the front of the previous j-1 transactions, placed in the previous i-1 days, and then let the first day of the first J transactions, then add at this point diff (Price[i]-price[i-1]) Greater than 0, then just can use the opportunity of this transaction to increase the profit (Profit = diff), otherwise, if the diff is less than 0, then on the day of the first day of trading, the number of transactions, but generate a profit of 0.

The second part is, Local[i-1][j]+diff, here's local[i-1][j] that the previous J-deal was completed in the first i-1 days, but because Local[a][b] must express the maximum profit of the B transaction in the first day, So it is necessary to force the transaction to occur on the first day, in order to achieve this, only on the basis of local[i-1][j], plus the diff (= price[i]-price[i-1]) on it. If diff < 0 there is no way, because the local definition must be met. When you calculate global, there is always a guarantee that you will get a larger value.


On the path of the full text of the problem analysis, Code Ganker is quite good. The following text extracts the author's analysis:

"This is the extension of best time to buy and Sell, and now we can do a maximum of two transactions," he said. We still use dynamic programming to do it, and in fact we can solve the very common situation, that is, the maximum number of transactions in the K-time.


Here we first explain the maximum number of K-trading algorithm, and then up to two times we only need to take K to 2 can be. We still use the "local and global optimal solution". We maintain two kinds of quantities, one is the current arrival of the first day can be a maximum of J transactions, the best profit is how much (Global[i][j]), the other is currently on the first day, the maximum number of J transactions, and the last transaction sold on the day the best profit is how much (Local[i][j]). Let's look at the recursive type below.

The overall situation is relatively simple,
Global[i][j]=max (Local[i][j],global[i-1][j]),
That is to go to the current local best, and the past the best in the big one (because the last transaction if the current day must be in the local best, otherwise it must be in the past the overall optimal inside).

For the maintenance of local variables, the recurrence type is
Local[i][j]=max (Global[i-1][j-1]+max (diff,0), Local[i-1][j]+diff),
That is to see two quantities, the first is the global to i-1 days to j-1 transactions, and then add today's transaction, if today is to make money (that is, the previous transaction as long as J-1, the last deal to take the current day), the second amount is to take the local i-1 day J transactions, And then add today's difference (here because local[i-1][j] such as contains the first I-1 day sell the transaction, so now becomes the first day sell, and will not increase the number of transactions, and here, regardless of the diff is greater than 0 must be added, because otherwise it is not satisfied local[i][j] Must be sold on the last day of the condition).

The above algorithm for the number of days to need a scan, and each time to the number of transactions to be recursive solution, so the time complexity is O (n*k), if it is a maximum of two transactions, then the complexity of O (n). The space only needs to maintain the day data is OK, therefore is O (k), when k=2, then is O (1). "


My Code:

/* Input:2, [6,1,3,2,4,7] output:6 expected:7 *//306ms public class Solution {public int maxprofit (int k, int[] 
        Prices) {int n = prices.length;
        
        Validate input 1 if (k <= 0 | | n = = 0) return 0;
        Validate input 2:if k is large enough, the question would be the same as question Ii.
            if (k >= n/2) {int result = 0; for (int i = 1; i < n; ++i) {if (Prices[i]-prices[i-1] > 0) {result = PRI
                Ces[i]-prices[i-1];
        } return result;
        } int[][] Localprofit = new Int[n][k + 1];

        int[][] Globalprofit = new Int[n][k + 1];
        In fact, it is not necessary to initialize K = 1 when the following nested for loop has been able to handle this initialization.
        int minprice = prices[0];
        for (int i = 1; i < n; ++i) {//localprofit[i][1]= prices[i]-minprice; Globalprofit[i][1]= Math.max (localprofit[i][1], globalPROFIT[I-1][1]);
        if (Prices[i] < Minprice) {//Minprice = Prices[i];
                (int j = 1; j <= K; ++j) {for (int i = 1; i < n; ++i) { 
                    Localprofit[i][j]= Math.max (Localprofit[i-1][j] + prices[i]-prices[i-1],
                Globalprofit[i-1][j-1] + math.max (0, Prices[i]-prices[i-1));
            GLOBALPROFIT[I][J] = Math.max (Localprofit[i][j], globalprofit[i-1][j]);
    } return globalprofit[n-1][k]; }
}


Resources:

1 Code ganker http://blog.csdn.net/linhuanmars/article/details/23236995

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.