Best Time to Buy and Sell Stock IV
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.
class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
if(prices.size() <= 1) return 0;
int n = prices.size();
//此处如果k的次数超过了数组长度的一半
if(k > n/2) return quickSolve(prices);
int trans = k;
vector<vector<int>> dp(trans + 1, vector<int>(prices.size(), 0));
for(int kk = 1; kk <= trans; kk++){
int tmpMax = dp[kk - 1][0] - prices[0];
for(int i = 1; i < prices.size(); i++){
dp[kk][i] = max(dp[kk][i - 1],prices[i]+tmpMax);
tmpMax = max(tmpMax,dp[kk - 1][i] - prices[i]);
}
}
return dp[k][n - 1];
}
int quickSolve(vector<int> &p){
int res = 0;
for(int i = 1; i < p.size(); i++){
if(p[i] > p[i - 1]) res += p[i] - p[i - 1];
}
return res;
}
};