有一个解决股票买卖问题(Best Time to Buy and Sell Stock)的模板,可以推广到买卖n次。
class Solution {
public:
int maxProfit(vector<int> &prices) {
// f[k, ii] represents the max profit up until prices[ii] (Note: NOT ending with prices[ii]) using at most k transactions.
// f[k, ii] = max(f[k, ii-1], prices[ii] - prices[jj] + f[k-1, jj]) { jj in range of [0, ii-1] }
// = max(f[k, ii-1], prices[ii] + max(f[k-1, jj] - prices[jj]))
// f[0, ii] = 0; 0 times transation makes 0 profit
// f[k, 0] = 0; if there is only one price data point you can't make any money no matter how many times you can trade
if (prices.size() <= 1) return 0;
else {
int K = 2; // number of max transation allowed
int maxProf = 0;
vector<vector<int>> f(K+1, vector<int>(prices.size(), 0));
for (int kk = 1; kk <= K; kk++) {
int tmpMax = f[kk-1][0] - prices[0];
for (int ii = 1; ii < prices.size(); ii++) {
f[kk][ii] = max(f[kk][ii-1], prices[ii] + tmpMax);
tmpMax = max(tmpMax, f[kk-1][ii] - prices[ii]);
maxProf = max(f[kk][ii], maxProf);
}
}
return maxProf;
}
}
};
另外,当k大于len/2时就可以用O(n)解决了,空间上的优化可以用翻滚数组,优化代码如下:
public class Solution {
public int maxProfit(int k, int[] prices) {
if (prices.length < 2) {
return 0;
} else {
if (k > prices.length / 2) {
return quickSolution(prices);
}
int[][] dp = new int[2][prices.length];
//int max = 0;
for (int kk = 1; kk <= k; kk ++) {
int tempPro = dp[(kk - 1) % 2][0] - prices[0];
for (int i = 1; i < prices.length; i ++) {
dp[kk % 2][i] = Math.max(dp[kk % 2][i - 1], prices[i] + tempPro);
tempPro = Math.max(tempPro, dp[(kk - 1) % 2][i] - prices[i]);
//max = Math.max(max, dp[kk % 2][i]);
}
}
return dp[k % 2][prices.length - 1];
}
}
private int quickSolution(int[] prices) {
int profile = 0;
for (int i = 1; i < prices.length; i ++) {
if (prices[i] > prices[i - 1]) {
profile += prices[i] - prices[i - 1];
}
}
return profile;
}
}