本文主要是介绍C语言 | Leetcode C语言题解之第188题买卖股票的最佳时机IV,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
题解:
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;
}
这篇关于C语言 | Leetcode C语言题解之第188题买卖股票的最佳时机IV的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!