Best Time to Buy and Sell Stock IV 来自 https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/discuss/ 题目描述:明确规定最多只能进行k次交易 将问题拆分成k个子问题,第0天到第cc天,第cc+1天到最后一天 用global和local来更新,考虑到第j天的交易可能跟第j-1天重复了 本来是1次交易但记录成两次 另外,如果k很大的时候,退化成第二种问题。注意,当k很大的时候,我们开数组的时候要小心,不然会爆掉,然后Runtime error local[j] = max(global[j-1]+max(diff,0), local[j]+diff); global[j] = max(local[j], global[j]);
class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
int size = prices.size();
if(size<2){
return0;
}
if(k>=size){
return solveMaxProfit(prices);
}
int local[k+1]={0};//k太大的时候 创建数组的时候爆掉了···int global[k+1]={0};
for(int i=0;i<size-1;i++){
int diff = prices[i+1]-prices[i];
for(int j=k;j>=1;j--){
local[j] = max(global[j-1]+max(diff,0), local[j]+diff);
global[j] = max(local[j], global[j]);
}
}
return global[k];
}
int solveMaxProfit(vector<int>& prices) {
int size = prices.size();
int result = 0;
for(int i=1;i<size;i++){
if(prices[i] - prices[i-1]>0){
result += prices[i]-prices[i-1];
}
}
return result;
}
};