Skip to content

Commit

Permalink
Update 0123.买卖股票的最佳时机III.md
Browse files Browse the repository at this point in the history
0123.买卖股票的最佳时机III新增C语言实现
  • Loading branch information
LYT0905 committed Mar 12, 2024
1 parent 1b9ae45 commit d40d61e
Showing 1 changed file with 28 additions and 1 deletion.
29 changes: 28 additions & 1 deletion problems/0123.买卖股票的最佳时机III.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
> 版本一
Expand Down Expand Up @@ -465,4 +493,3 @@ impl Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

0 comments on commit d40d61e

Please sign in to comment.