LeetCode-123.Best Time to Buy and Sell Stock III

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most twotransactions.

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Example 1:

Input: [3,3,5,0,0,3,1,4]
Output: 6
Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
             Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.

Example 2:

Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
             Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
             engaging multiple transactions at the same time. You must sell before buying again.

Example 3:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

通用只能执行k此买卖
 1     public int maxProfit(int[] prices) {//dp my
 2         if(null==prices||0==prices.length){
 3             return 0;
 4         }
 5         int max =0;
 6         int k=2;
 7         int[][] states = new int[k+1][2];
 8         states[0][1] = -prices[0];
 9         for(int i=0;i<=k;i++){
10             states[i][1]=-prices[0];
11         }
12         for(int i=1;i<prices.length;i++){
13             for(int j=0;j<=k;j++){
14                 states[j][1] = Math.max(states[j][1],states[j][0]-prices[i]);
15                 if(j==0){
16                     states[j][0] = states[j][0];
17                 }
18                 else{
19                     states[j][0] = Math.max(states[j][0],states[j-1][1]+prices[i]);
20                 }
21 
22             }
23         }
24         for(int i=0;i<=k;i++){
25             max = max>states[i][0]?max:states[i][0];
26         }
27         
28         return max;
29     }

相关题

买卖股票的最佳时间1 LeetCode121 https://www.cnblogs.com/zhacai/p/10429264.html

买卖股票的最佳时间2 LeetCode122 https://www.cnblogs.com/zhacai/p/10596627.html

买卖股票的最佳时间4 LeetCode188 https://www.cnblogs.com/zhacai/p/10645522.html

买卖股票的最佳时间冷冻期 LeetCode309 https://www.cnblogs.com/zhacai/p/10655970.html

买卖股票的最佳时间交易费 LeetCode714 https://www.cnblogs.com/zhacai/p/10659288.html

原文地址:https://www.cnblogs.com/zhacai/p/10645571.html