## leetcode：买卖股票的最佳时机2（python）

LeetCode 股票 最佳 买卖 最佳时机

## 2.1 常规思路

### 2.1 python常规代码

``````class Solution:
def maxProfit(self, prices: List[int]) -> int:
if len(prices) == 0:
return 0
profit = 0
for i in range(len(prices)-1):
if prices[i+1] > prices[i]:
profit += (prices[i+1] - prices[i])
return profit
``````

## 2.2 动态规划

### 2.2 动态规划代码

``````class Solution:
def maxProfit(self, prices: List[int]) -> int:
if len(prices) == 0:
return 0
n = len(prices)
dp = [[0 for i in range(2)] for i in range(n)]
dp[0][0] = 0
dp[0][1] = -prices[0]
for i in range(1,n):
dp[i][0] = max(dp[i-1][0],dp[i-1][1]+prices[i])
dp[i][1] = max(dp[i-1][1],dp[i-1][0]-prices[i])
return dp[n-1][0]
``````

### 优化代码

``````class Solution:
def maxProfit(self, prices: List[int]) -> int:
if len(prices) == 0:
return 0
n = len(prices)
dp_i_0 = 0
dp_i_1 = -prices[0]
for i in range(1,n):
dp_i_0 = max(dp_i_0,dp_i_1+prices[i])
dp_i_1 = max(dp_i_1,dp_i_0-prices[i])
return dp_i_0
``````

https://blog.csdn.net/ggdhs/article/details/92384316