Problem 188: Best Time to Buy and Sell Stock IV
思路
public class Solution {
public int maxProfit(int k, int[] prices) {
if (k < 1) return 0;
if (prices == null || prices.length <= 1) return 0;
int len = prices.length;
if (k >= len / 2) {
return helper(prices);
}
int[] buy = new int[k + 1];
int[] sell = new int[k + 1];
Arrays.fill(buy, Integer.MIN_VALUE);
for (int i = 0; i < prices.length; i++) {
for (int j = k; j > 0; j--) {
sell[j] = Math.max(sell[j], prices[i] + buy[j]);
buy[j] = Math.max(buy[j], sell[j - 1] - prices[i]);
}
}
return sell[k];
}
private int helper(int[] prices) {
int profit = 0;
for (int i = 0; i < prices.length - 1; i++) {
int diff = prices[i + 1] - prices[i];
if (diff > 0) {
profit += diff;
}
}
return profit;
}
}易错点
PreviousProblem 123: Best Time to Buy and Sell Stock IIINextProblem 309: Best Time to Buy and Sell Stock with Cooldown
Last updated