mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Merge pull request #355 from z80160280/z80160280-patch-4
Update 0123.买卖股票的最佳时机III.md
This commit is contained in:
@ -229,6 +229,40 @@ class Solution { // 动态规划
|
|||||||
|
|
||||||
Python:
|
Python:
|
||||||
|
|
||||||
|
> 版本一:
|
||||||
|
```python
|
||||||
|
class Solution:
|
||||||
|
def maxProfit(self, prices: List[int]) -> int:
|
||||||
|
if len(prices) == 0:
|
||||||
|
return 0
|
||||||
|
dp = [[0] * 5 for _ in range(len(prices))]
|
||||||
|
dp[0][1] = -prices[0]
|
||||||
|
dp[0][3] = -prices[0]
|
||||||
|
for i in range(1, len(prices)):
|
||||||
|
dp[i][0] = dp[i-1][0]
|
||||||
|
dp[i][1] = max(dp[i-1][1], dp[i-1][0] - prices[i])
|
||||||
|
dp[i][2] = max(dp[i-1][2], dp[i-1][1] + prices[i])
|
||||||
|
dp[i][3] = max(dp[i-1][3], dp[i-1][2] - prices[i])
|
||||||
|
dp[i][4] = max(dp[i-1][4], dp[i-1][3] + prices[i])
|
||||||
|
return dp[-1][4]
|
||||||
|
```
|
||||||
|
|
||||||
|
> 版本二:
|
||||||
|
```python
|
||||||
|
class Solution:
|
||||||
|
def maxProfit(self, prices: List[int]) -> int:
|
||||||
|
if len(prices) == 0:
|
||||||
|
return 0
|
||||||
|
dp = [0] * 5
|
||||||
|
dp[1] = -prices[0]
|
||||||
|
dp[3] = -prices[0]
|
||||||
|
for i in range(1, len(prices)):
|
||||||
|
dp[1] = max(dp[1], dp[0] - prices[i])
|
||||||
|
dp[2] = max(dp[2], dp[1] + prices[i])
|
||||||
|
dp[3] = max(dp[3], dp[2] - prices[i])
|
||||||
|
dp[4] = max(dp[4], dp[3] + prices[i])
|
||||||
|
return dp[4]
|
||||||
|
```
|
||||||
|
|
||||||
Go:
|
Go:
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user