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.
解题思路:
本题是Best Time to Buy and Sell Stock系列最难的一道,需要用到dp,JAVA实现如下:
public int maxProfit(int k, int[] prices) { if (k == 0 || prices.length < 2) return 0; if (k > prices.length / 2) { int maxProfitII = 0; for (int i = 1; i < prices.length; ++i) if (prices[i] > prices[i - 1]) maxProfitII += prices[i] - prices[i - 1]; return maxProfitII; } int[] buy=new int[k]; int[] sell=new int[k]; for(int i=0;i<buy.length;i++) buy[i]=Integer.MIN_VALUE; for (int i = 0; i < prices.length; i++) for (int j = k - 1; j >= 0; j--) { sell[j] = Math.max(sell[j], buy[j] + prices[i]); if (j == 0) buy[j] = Math.max(buy[j], -prices[i]); else buy[j] = Math.max(buy[j], sell[j - 1] - prices[i]); } return sell[k - 1]; }
时间: 2024-10-07 18:58:44