题目描述
You are given an integer array prices where prices[i] is the price of a given stock on the ith day.
Design an algorithm to find the maximum profit. You may complete at most k transactions.
样例
Input: k = 2, prices = [3,2,6,5,0,3]
Output: 7
Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
算法1
(DP) $O(n^2)$
C++ 代码
class Solution {
public:
int maxProfit(int k, vector<int> &prices) {
int size = (int)prices.size();
if (k==0||size<2) {
return 0;
}
if (k>size/2) {
int sum = 0;
for(int i = 1;i < size;i++){
if(prices[i] > prices[i-1]){
sum += prices[i] - prices[i-1];
}
}
return sum;
}
vector<int> buy(k,INT_MIN);
vector<int> sell(k,0);
for (int i=0; i<size; i++) {
for (int j=k-1; j>=0; j--) {
sell[j]=max(sell[j],buy[j]+prices[i]);
buy[j]=max(buy[j],(j>0?sell[j-1]:0)-prices[i]);
}
}
return sell[k-1];
}