Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit ddc675b

Browse files
🐱(dynamic): 123. 买卖股票的最佳时机 III
1 parent cc8d23a commit ddc675b

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

‎docs/algorithm/dynamic/README.md‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -485,6 +485,57 @@ class Solution(object):
485485
return dp[n]
486486
```
487487

488+
## 123. 买卖股票的最佳时机 III
489+
490+
[原题链接](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iii/)
491+
492+
### 思路
493+
494+
这个系列的题真是折磨人呐。首先还是要先确定需要记录几个状态值。
495+
496+
对于某一天来说,可能会发生的情况:
497+
498+
1. 第一次被买入
499+
2. 第一次被卖出
500+
3. 第二次被买入
501+
4. 第二次被卖出
502+
503+
按题目要求,我们最重要求出的是**第二次被卖出**所能获得的最大收益。
504+
505+
我们分别用 4 个变量来表示这 4 种情况下所能获得的最大收益:
506+
507+
1. 在某天完成第一次买入的最大收益 `first_buy`
508+
2. 在某天完成第一次被卖出的最大收益 `first_sell`
509+
3. 在某天完成第二次被买入的最大收益 `second_buy`
510+
4. 在某天完成第二次被卖出最大收益 `second_sell`
511+
512+
可以得出状态转移公式:
513+
514+
```
515+
first_buy = max(first_buy, -price)
516+
first_sell = max(first_sell, first_buy + price)
517+
second_buy = max(second_buy, first_sell - price)
518+
second_sell = max(second_sell, second_buy + price)
519+
```
520+
521+
其中 `price` 为某天股票的价格。
522+
523+
```python
524+
class Solution:
525+
def maxProfit(self, prices: List[int]) -> int:
526+
first_buy = float('-inf')
527+
first_sell = 0
528+
second_buy = float('-inf')
529+
second_sell = 0
530+
531+
for price in prices:
532+
first_buy = max(first_buy, -price)
533+
first_sell = max(first_sell, first_buy + price)
534+
second_buy = max(second_buy, first_sell - price)
535+
second_sell = max(second_sell, second_buy + price)
536+
537+
return second_sell
538+
```
488539

489540
## 152. 乘积最大子序列
490541

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /