题目:
题解:
int maxProfit(int k, int* prices, int pricesSize) {
int n = pricesSize;
if (n == 0) {
return 0;
}
k = fmin(k, n / 2);
int buy[k + 1], sell[k + 1];
memset(buy, 0, sizeof(buy));
memset(sell, 0, sizeof(sell));
buy[0] = -prices[0];
sell[0] = 0;
for (int i = 1; i <= k; ++i) {
buy[i] = sell[i] = INT_MIN / 2;
}
for (int i = 1; i < n; ++i) {
buy[0] = fmax(buy[0], sell[0] - prices[i]);
for (int j = 1; j <= k; ++j) {
buy[j] = fmax(buy[j], sell[j] - prices[i]);
sell[j] = fmax(sell[j], buy[j - 1] + prices[i]);
}
}
int ret = 0;
for (int i = 0; i <= k; i++) {
ret = fmax(ret, sell[i]);
}
return ret;
}