mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Merge pull request #354 from z80160280/z80160280-patch-3
Update 0122.买卖股票的最佳时机II(动态规划).md
This commit is contained in:
@ -171,6 +171,33 @@ class Solution
|
||||
|
||||
Python:
|
||||
|
||||
> 版本一:
|
||||
```python
|
||||
class Solution:
|
||||
def maxProfit(self, prices: List[int]) -> int:
|
||||
length = len(prices)
|
||||
dp = [[0] * 2 for _ in range(length)]
|
||||
dp[0][0] = -prices[0]
|
||||
dp[0][1] = 0
|
||||
for i in range(1, length):
|
||||
dp[i][0] = max(dp[i-1][0], dp[i-1][1] - prices[i]) #注意这里是和121. 买卖股票的最佳时机唯一不同的地方
|
||||
dp[i][1] = max(dp[i-1][1], dp[i-1][0] + prices[i])
|
||||
return dp[-1][1]
|
||||
```
|
||||
|
||||
> 版本二:
|
||||
```python
|
||||
class Solution:
|
||||
def maxProfit(self, prices: List[int]) -> int:
|
||||
length = len(prices)
|
||||
dp = [[0] * 2 for _ in range(2)] #注意这里只开辟了一个2 * 2大小的二维数组
|
||||
dp[0][0] = -prices[0]
|
||||
dp[0][1] = 0
|
||||
for i in range(1, length):
|
||||
dp[i % 2][0] = max(dp[(i-1) % 2][0], dp[(i-1) % 2][1] - prices[i])
|
||||
dp[i % 2][1] = max(dp[(i-1) % 2][1], dp[(i-1) % 2][0] + prices[i])
|
||||
return dp[(length-1) % 2][1]
|
||||
```
|
||||
|
||||
Go:
|
||||
|
||||
|
Reference in New Issue
Block a user