Leetcode-best time to Buy and Sell Stock I II III IV

Source: Internet
Author: User

Here are three questions with maximum subarray, you can look at this question first

I)

Say you has an array for which the i-th element is the price of a given-stock on day I.

If you were-permitted-to-complete at most one transaction (ie, buy one and sell one share of the stock), design an AL Gorithm to find the maximum profit.

The first, dynamic programming algorithm for this problem. State transfer equation F (i) = Max (Maxprofit, Prices[i]-minprice)

    public int Maxprofit (int[] prices) {        int maxPro = 0;        int minprice = Integer.max_value;        for (int i = 0; i < prices.length; i++) {            minprice = math.min (Minprice, prices[i]);            MaxPro = Math.max (MaxPro, Prices[i]-minprice);        }        return maxPro;    }
The algorithm traverses the array backwards, minprice refers to prices[0...i] 's minimum value, Maxpro is the maximum profit in PRICES[0...I]

Of course, you can also traverse forward from behind, as follows:

    public int Maxprofit (int[] prices) {        if (prices = = NULL | | prices.length = 0) return 0;int max = Prices[prices.length -1];int maxprofit = 0;for (int i = prices.length-1; I >= 0; i--) {max = Math.max (max, prices[i]); maxprofit = Math.max (M Axprofit, Max-prices[i]);} return maxprofit;    }
Max refers to the maximum value of prices[i...n-1], Maxpro refers to the maximum profit in prices[i...n-1]

There is also a solution, as follows:

    public int Maxprofit (int[] prices) {        int maxPro = 0;        int maxcur = 0;        for (int i = 1; i < prices.length; i++) {            maxcur = Math.max (0, Maxcur + = Prices[i]-prices[i-1]);            MaxPro = Math.max (MaxPro, maxcur);        }        return maxPro;    }
II)

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 could complete as many transactions as (ie, buy one and sell one share of the stock multiple times). However, engage in multiple transactions for the same time (ie, you must sell the stock before you buy again).

The second question, no limit on the number of times, is obviously greedy algorithm, as follows:

    public int Maxprofit (int[] prices) {        if (prices = = NULL | | prices.length = = 0) return 0;        int max = 0;        for (int i = 1; i < prices.length; i++) {            if (Prices[i]-prices[i-1] > 0) Max + = Prices[i]-prices[i-1];        }        return max;    }
III)

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).

The third problem is limited to a maximum of two trades, so we can follow the first question. Break the problem down to trade once before I, and trade once after I. The state transition equation is:

F (2, 0, n) = max{f (1, 0, i) +f (1, I, n)} i = 1, 2, 3...N where F (k, M, n) represents the maximum profit for trading K times directly in the PRICES[M...N, the code is as follows:

public int maxProfit1 (int[] prices) {    if (prices = = NULL | | prices.length = = 0) return 0;    int max = 0;    for (int i = 0; i < prices.length; i++) {    int curprofit = maxProfit1 (prices, 0, I) + maxProfit1 (prices, I, PRICES.L Ength);    max = Math.max (max, curprofit);    }    return max;    }    private int maxProfit1 (int[] prices, int s, int e) {    if (S > E) return 0;    int min = prices[s];    int maxprofit = 0;    for (int i = s; i < E; i++) {    min = math.min (min, prices[i]);    Maxprofit = Math.max (Maxprofit, prices[i]-min);    }    return maxprofit;    }
The code timed out because there were duplicate sub-issues. So we can save the result in the array based on the problem I, after the query.

    public int Maxprofit (int[] prices) {        if (prices = = NULL | | prices.length = = 0) return 0;    int max = 0;    Maximum profit at end of I, i.e. [0...i]    int[] Maxeh = maxendinghere (prices);    The maximum profit starting with I, i.e. [I...N]    int[] maxbh = maxbegininghere (prices);    for (int i = 0; i < prices.length; i++) {    int curprofit = maxeh[i]+maxbh[i];    max = Math.max (max, curprofit);    }    return Max;} Private int[] Maxendinghere (int[] prices) {int[] ret = new Int[prices.length];int min = prices[0];for (int i = 1; i < P Rices.length; i++) {min = math.min (min, prices[i]); Ret[i] = Math.max (ret[i-1], prices[i]-min);} return ret;}  Private int[] Maxbegininghere (int[] prices) {int[] ret = new Int[prices.length];int max = prices[prices.length-1];for (int i = prices.length-1; i > 0; i--) {max = Math.max (max, prices[i]); Ret[i] = Math.max (Ret[i-1], max-prices[i]);} return ret;    }
Of course, you can combine three loops in your code into two. There are other solutions to this problem, which will be explained in a minute.

IV)

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).

The hardest one is to write the state transfer equation first.

F (k, i) = max{f (k, i-1), max {f (k-1, j-1) +prices[i]-prices[j]}} j = 0, 1, 2...i-1
F (0, I) = 0, f (k, 0) = 0

where F (k,i) refers to the maximum profit from the PRICES[0...I],K exchange, the analysis of the state transition equation, for prices[i], there are two options:

1) Do not participate, the problem is degraded to the premise of K-transactions, only with prices[0...i-1], that is f (k, i)

2) Participate in the transaction, then I must be the price for the sale, because this is the last day of the transaction. So there is prices[i]-prices[j] + f (k-1, j-1) j = 0. 1. i-1 Find Maximum Value

The maximum value is obtained for the above problem.

The code is as follows:

    public int Maxprofit (int k, int[] prices) {if (prices = = NULL | | prices.length = = 0) return 0;        if (k >= prices.length/2) {//Degenerate Problematic II return Maxprofit (prices); }//f (k, i) = max{f (k, i-1), max {f (k-1, j-1) +prices[i]-prices[j]}} j = 0, 1, 2...i-1//f (0, I) = 0, F (k , 0) = 0//f (k, i) = max{f (k, i-1), Prices[i]+max {f (k-1, j-1)-prices[j]}} j = 0, 1, 2...i-1//Order Tempmax        = max {f (k-1, j-1)-prices[j]} j = 0, 1, 2...i-1 int[][] dp = new Int[k+1][prices.length];        for (int i = 1; I <= K; i++) {int tempmax =-prices[0];        for (int j = 1; j < Prices.length; J + +) {Dp[i][j] = Math.max (Dp[i][j-1], tempmax+prices[j]);        Tempmax = Math.max (Tempmax, dp[i-1][j-1]-prices[j]);    }} return dp[k][prices.length-1];        } public int Maxprofit (int[] prices) {if (prices = = NULL | | prices.length = 0) return 0;        int max = 0; for (int i = 1; i <Prices.length;        i++) {if (Prices[i]-prices[i-1] > 0) Max + = prices[i]-prices[i-1];    } return max; }
Among them, Tempmax refers to the i-1 transactions, and only with the former j-1 prices, and at this time has bought PRICE[J] the maximum value. The inner loop is always looking for the maximum value of the stock that has been i-1 traded and bought Prices[j]. TEMPMAX+PRICES[J] refers to a stock that has been bought before, and is now to be sold at Prices[j]

With the above solution, the problem three also has a new solution, namely k=2. But there is a simpler way of expressing it. As follows:

public int Maxprofit (int[] prices) {        int hold1 = integer.min_value, hold2 = Integer.min_value;        int release1 = 0, release2 = 0;        for (int i:prices) {                              //Assume we only has 0 money at first            release2 = Math.max (Release2, hold2+i);     The maximum if we ' ve just sold 2nd stock so far.            Hold2    = Math.max (hold2,    release1-i);  The maximum if we ' ve just buy  2nd stock so far.            Release1 = Math.max (release1, hold1+i);     The maximum if we ' ve just sold 1nd stock so far.            Hold1    = Math.max (hold1,-i    );          The maximum if we ' ve just buy  1st stock so far.         }        return RELEASE2; Since RELEASE1 is initiated as 0, so Release2 would always higher than release1.    }
In fact, it is based on the above recursive formula.












Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Leetcode-best time to Buy and Sell Stock I II III 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.