Java for LeetCode 188 Best Time to Buy and Sell Stock IV【HARD】
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.
解题思路:
https://leetcode.com/discuss/18330/is-it-best-solution-with-o-n-o-1%E3%80%82
本题是Best Time to Buy and Sell Stock系列最难的一道,
参考Java for LeetCode 123 Best Time to Buy and Sell Stock III解法二的思路,四个数组可以压缩为两个数组,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]; }