# LeetCode Best Time to Buy and Sell Stock IV

LeetCode 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.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

1. mustSell[i][j]=max(globalBest[i-1][j-1]+profit, mustSell[i-1][j]+profit)
2. globalBest[i][j]=max(globalBest[i-1][j], mustSell[i][j])

```class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
int days = prices.size();
if (days < 2)return 0;
if (k >= days / 2) {
int ans = 0;
for (int i = 1; i < days; ++i) {
if (prices[i] > prices[i - 1])ans += (prices[i] - prices[i - 1]);
}
return ans;
}
vector<vector<int>> mustSell(days, vector<int>(k + 1, 0)), globalBest(days, vector<int>(k + 1, 0));
for (int i = 1; i < days; ++i) {
int profit = prices[i] - prices[i - 1];
for (int j = 1; j <= k; ++j) {
mustSell[i][j] = max(globalBest[i - 1][j - 1] + profit, mustSell[i - 1][j] + profit);
globalBest[i][j] = max(globalBest[i - 1][j], mustSell[i][j]);
}
}
return globalBest[days - 1][k];
}
};
```