From d40d61e265e33deddc2d84daacd52eb85afb5496 Mon Sep 17 00:00:00 2001 From: a12bb <2713204748@qq.com> Date: Tue, 12 Mar 2024 21:44:50 +0800 Subject: [PATCH] =?UTF-8?q?Update=200123.=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=BAIII.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0123.买卖股票的最佳时机III新增C语言实现 --- .../0123.买卖股票的最佳时机III.md | 29 ++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/problems/0123.买卖股票的最佳时机III.md b/problems/0123.买卖股票的最佳时机III.md index 72dd9042..18f19c51 100644 --- a/problems/0123.买卖股票的最佳时机III.md +++ b/problems/0123.买卖股票的最佳时机III.md @@ -413,6 +413,34 @@ function maxProfit(prices: number[]): number { }; ``` +### C: + +```c +#define max(a, b) ((a) > (b) ? (a) : (b)) +#define min(a, b) ((a) > (b) ? (b) : (a)) + +int maxProfit(int* prices, int pricesSize) { + int buy1 = prices[0], buy2 = prices[0]; + int profit1 = 0, profit2 = 0; + for (int i = 0; i < pricesSize; ++i) { + // 寻找最低点买入 + buy1 = min(buy1, prices[i]); + // 找到第一次交易的最大盈利,并不断维护这一最大值 + profit1 = max(profit1, prices[i] - buy1); + + // 寻找第二次交易的最低投资点,并且考虑前一次交易的成本 + // 当前价格 - 第一次操作的盈利=新的投入成本( + // 为了让盈利最大,要寻找最小的成本) + buy2 = min(buy2, prices[i] - profit1); + // 第二次卖出后的盈利:当前价格减去成本,不断维护这一最大的总利润 + profit2 = max(profit2, prices[i] - buy2); + } + return profit2; +} +``` + + + ### Rust: > 版本一 @@ -465,4 +493,3 @@ impl Solution { -