Dynamic Programming Leetcode of topics (DP) -123. The best time to buy and sell stocks III (Best Time to Buy and Sell Stock III)

Dynamic Programming Leetcode of topics (DP) -123. The best time to buy and sell stocks III (Best Time to Buy and Sell Stock III)

Stock issues:

121. The best time to stock trading

122. The best time to trade stocks II

III 123. the best time to buy and sell stocks

188. The best time to buy and sell stocks IV

309. The best time to buy and sell shares with the freezing of

714. The best time to buy and sell stocks with fee


 

Given an array, its first  i  element is a given stock at the  price day.

Design an algorithm to compute the maximum profit you can get. You can complete up to  two pen  transactions.

Note: You can not simultaneously involved in multiple transactions (you must sell before buying shares again before the fall).

Example 1:

Input: [3,3,5,0,0,3,1,4] 
Output: 6 
Explanation: Day 4 (stock price = 0) when buying on day 6 (stock price = 3) when to sell, this transaction can profit = 3-0 = 3. 
     Then, on day 7 (stock price = 1) when buying on day 8 (stock price = 4), when sold, this transaction can profit = 4-1 = 3.

Example 2:

Enter: [1,2,3,4,5] 
Output: 4 
to explain: (stock price = 1) when buying on Day 1, on Day 5 (stock price = 5), when sold, this Exchange can profit = 5-1 = 4.   
     Note that you can not buy stock in a series of 1 and day 2, then after they are sold.   
     Because it belongs to the same time involved in multiple transactions, you have to sell the stock before the fall before buying again.

Example 3:

Enter: [7,6,4,3,1] 
Output: 0 
to explain: in this case, no transaction is completed, the maximum profit is zero.

Limit for 2 times. 

dp [i] [0] [ k] represents the i day does not own shares and the maximum number of transactions is k times the maximum profit.
dp [i] [1] [ k] represents the i-day holding shares and the maximum number of transactions is k times the maximum profit. 

Detailed look at a few other stock issues.

class Solution {
    public int maxProfit(int[] prices) {
        if(prices==null || prices.length==0) return 0;
        int k = 2;
        int[][][] dp = new int[prices.length][2][k+1];
        for (int i = 0; i < k+1; i++) {
            dp[0][0][i] = 0;
            dp[0][1][i] = -prices[0];
        }
        for (int i = 1; i < prices.length; i++) {
            for (int k1 = 1; k1 <= k; k1++) {
                dp[i][0][k1] = Math.max(dp[i-1][0][k1],dp[i-1][1][k1]+prices[i]);
                dp[i][1][k1] = Math.max(dp[i-1][1][k1],dp[i-1][0][k1-1]-prices[i]);
            }
        }
        return dp[prices.length-1][0][k];
    }
}

 

Guess you like

Origin www.cnblogs.com/qinyuguan/p/11487720.html