188. Best Time to Buy and Sell Stock IV
188. Best Time to Buy and Sell Stock IV
cofama 发表于12个月前
188. Best Time to Buy and Sell Stock IV
• 发表于 12个月前
• 阅读 1
• 收藏 0
• 评论 0

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. Note: You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

``````class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
if(prices.empty()) return 0;
if(prices.size()<=k*2) {
int profit=0;
for(int i=1; i<prices.size(); i++) {
if(prices[i]>prices[i-1]) {
profit += prices[i]-prices[i-1];
}
}
return profit;
}

int dp[prices.size()][k+1];
for(int i=0; i<prices.size(); i++)
dp[i][0]=0;
for(int j=1; j<=k; j++)
dp[0][j]=0;

for(int j=1; j<=k; j++) {
for(int i=1; i<prices.size(); i++) {
if(prices[i]>prices[i-1]) {
}
else {
dp[i][j] = dp[i-1][j];
}
}
}

return dp[prices.size()-1][k];
}
};
``````

×