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.

 

 1 public class Solution {

 2     public int maxProfit(int k, int[] prices) {

 3         if(prices == null || prices.length == 0) return 0;

 4         int len = prices.length;

 5         if (k >= len / 2) return quickSolve(prices);

 6         int[][] dp = new int[k + 1][len];

 7         for (int i = 1; i <= k; i++) {

 8             int tmpMax = -prices[0];

 9             for(int j = 1; j < len; j ++){

10                 dp[i][j] = Math.max(dp[i][j - 1], prices[j] + tmpMax);

11                 tmpMax = Math.max(tmpMax, dp[i - 1][j - 1] - prices[j]);

12             }

13         }

14         return dp[k][len - 1];

15     }

16     

17     public int quickSolve(int[] prices){

18         int result = 0;

19         for(int i = 1; i < prices.length; i ++){

20             if(prices[i] - prices[i - 1] > 0) result += prices[i] - prices[i - 1];

21         }

22         return result;

23     }

24 }

tmpMax means the maximum profit of just doing at most i-1 transactions, using at most first j-1 prices, and buying the stock at price[j] - this is used for the next loop.

 

 1 public class Solution {

 2     public int maxProfit(int k, int[] prices) {

 3         if(prices == null || prices.length < 2 || k == 0) return 0;

 4         int len = prices.length;

 5         if(k * 2 >= len){//actually we can do as many transactions as we want

 6             int result = 0;

 7             for(int i = 1; i < len; i ++){

 8                 if(prices[i] - prices[i - 1] > 0) result += prices[i] - prices[i - 1];

 9             }

10             return result;

11         }else{//transactions time is limited

12             int[][] dp = new int[k + 1][len];

13             for(int i = 1; i <= k; i ++){

14                 int MaxPre = -prices[0];

15                 for(int j = 1; j < len; j ++){

16                     dp[i][j] = Math.max(dp[i][j - 1], MaxPre + prices[j]);

17                     MaxPre = Math.max(MaxPre, dp[i - 1][j - 1] - prices[j]);

18                 }

19             }

20             return dp[k][len - 1];

21         }

22     }

23 }

 

你可能感兴趣的:(time)