Say you have an array for which the ith element is the price of a given stock on dayi.
Design an algorithm to find the maximum profit. You may complete at mostk 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.
题目链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/
题目分析:股票系列最后一题,最多买k次,对于两次的时候有这样一种很好理解的解法:
for (int price : prices) {
sell2 = Math.max(sell2, buy2 + price);
buy2 = Math.max(buy2, sell1 - price);
sell1 = Math.max(sell1, buy1 + price);
buy1 = Math.max(buy1, -price);
}
然后推广的k次,实际上就是加一层循环,有一个优化,如果k >= n / 2,相当于可以买无限次,直接用无限次的做法On扫一下即可
public class Solution {
public int maxProfit(int k, int[] prices) {
int n = prices.length;
if (n < 2) {
return 0;
}
if (k >= n / 2) {
int ans = 0;
for (int i = 0; i < n - 1; i++) {
if (prices[i + 1] > prices[i]) {
ans += prices[i + 1] - prices[i];
}
}
return ans;
}
else {
int[] sell = new int[n + 1];
int[] buy = new int[n + 1];
for (int i = 1; i <= n; i++) {
buy[i] = -0x3fffffff;
}
for (int i = 0; i < n; i++) {
for (int j = k; j >= 1; j--) {
sell[j] = Math.max(sell[j], buy[j] + prices[i]);
buy[j] = Math.max(buy[j], sell[j - 1] - prices[i]);
}
}
return sell[k];
}
}
}