LeetCode-Best Time to Buy and Sell Stock IV

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 k transactions.

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

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

Analysis:

DP formula is

hold[i][j] = Math.max(hold[i][j-1], unhold[i][j-1]-prices[j]);

unhold[i][j] = Math.max(unhold[i][j-1], hold[i-1][j-1]+prices[j]);

Solution:

 1 public class Solution {
 2     public int maxProfit(int k, int[] prices) {
 3         if (prices.length<2) return 0;
 4         int len = prices.length;
 5         
 6         // IMPORTANT: you can skip calculation if you are allowed to perform the max times of transactions. 
 7         if (k>=len/2){
 8             int profit = 0;
 9             for (int i=1;i<len;i++)
10                 if (prices[i] > prices[i-1])
11                     profit += (prices[i] - prices[i-1]);
12             return profit;
13         }
14         
15         int[] hold = new int[len];
16         int[] unhold = new int[len];
17         
18         hold[0] = -prices[0];
19         for (int i=1;i<len;i++)
20             hold[i] = Math.max(hold[i-1], -prices[i]);
21 
22         
23         for (int i=1;i<=k;i++){
24             int lastHold = hold[0];
25             hold[0] = -prices[0];
26             for (int j=1;j<len;j++){
27                 lastHold = hold[j];
28                 hold[j] = Math.max(hold[j-1], unhold[j-1]-prices[j]);
29                 unhold[j] = Math.max(unhold[j-1], lastHold+prices[j]);
30             }
31         }
32             
33         return Math.max(hold[len-1],unhold[len-1]);
34     }
35 }

 

posted @ 2016-07-22 14:45  LiBlog  阅读(198)  评论(0编辑  收藏  举报