From d91656d036e536637138ebe7c51c8a37eda01bc2 Mon Sep 17 00:00:00 2001 From: a12bb <2713204748@qq.com> Date: Tue, 12 Mar 2024 21:46:06 +0800 Subject: [PATCH] =?UTF-8?q?Update=200188.=E4=B9=B0=E5=8D=96=E8=82=A1?= =?UTF-8?q?=E7=A5=A8=E7=9A=84=E6=9C=80=E4=BD=B3=E6=97=B6=E6=9C=BAIV.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0188.买卖股票的最佳时机IV新增C语言实现 --- .../0188.买卖股票的最佳时机IV.md | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/problems/0188.买卖股票的最佳时机IV.md b/problems/0188.买卖股票的最佳时机IV.md index e4c5c484..2521749f 100644 --- a/problems/0188.买卖股票的最佳时机IV.md +++ b/problems/0188.买卖股票的最佳时机IV.md @@ -474,6 +474,34 @@ function maxProfit(k: number, prices: number[]): number { }; ``` +### C: + +```c +#define max(a, b) ((a) > (b) ? (a) : (b)) + +int maxProfit(int k, int* prices, int pricesSize) { + if(pricesSize == 0){ + return 0; + } + + int dp[pricesSize][2 * k + 1]; + memset(dp, 0, sizeof(int) * pricesSize * (2 * k + 1)); + for (int j = 1; j < 2 * k; j += 2) { + dp[0][j] = -prices[0]; + } + + for (int i = 1;i < pricesSize; i++) {//枚举股票 + for (int j = 0; j < 2 * k - 1; j += 2) { //更新每一次买入卖出 + dp[i][j + 1] = max(dp[i - 1][j + 1], dp[i - 1][j] - prices[i]); + dp[i][j + 2] = max(dp[i - 1][j + 2], dp[i - 1][j + 1] + prices[i]); + } + } + return dp[pricesSize - 1][2 * k]; +} +``` + + + ### Rust: ```rust @@ -529,3 +557,4 @@ impl Solution { +