# [Leetcode][python]Best Time to Buy and Sell Stock I/II/III/买卖股票的最佳时机

【Leetcode题解】 同时被 2 个专栏收录
146 篇文章 0 订阅
145 篇文章 10 订阅

# Best Time to Buy and Sell Stock

DP或者直接解决

## 代码

### DP

dp[i] = max(dp[i - 1], prices[i] - minPrice)
minPrice永远是之前的最底价格

class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
dp = [0 for __ in range(len(prices))]
minPrice = prices[0]
for i in range(1, len(prices)):
dp[i] = max(dp[i - 1], prices[i] - minPrice)
if(minPrice > prices[i]):
minPrice = prices[i]
return dp[-1]

### 直接解法

class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices :
return 0
ans, money, n = 0, prices[0], len(prices)
for i in range(n):
ans = max(ans, prices[i]-money)
money = min(prices[i], money)
return ans

# Best Time to Buy and Sell Stock II

## 代码

class Solution:
# @param prices, a list of integer
# @return an integer
def maxProfit(self, prices):
maxprofit = 0
for i in range(1, len(prices)):
if prices[i] >= prices[i-1]:
maxprofit += prices[i] - prices[i-1]
return maxprofit

# Best Time to Buy and Sell Stock III

## 代码

class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
length = len(prices)
if length==0:
return 0
f1 = [0 for __ in range(length)]
f2 = [0 for __ in range(length)]
# 从前往后最大利润
minPrice = prices[0]
for i in range(1, length):
f1[i] = max(f1[i-1], prices[i]-minPrice)
minPrice=min(minPrice, prices[i])
# 从后往前则是最小利润
maxPrice = prices[length-1]
for i in range(length-2,-1,-1):
f2[i] = max(f2[i+1], maxPrice-prices[i])
maxPrice = max(maxPrice, prices[i])

maxProfit=0
for i in range(length):
if f1[i]+f2[i] > maxProfit:
maxProfit = f1[i]+f2[i]
return maxProfit

# 总结

• 0
点赞
• 0
评论
• 1
收藏
• 一键三连
• 扫一扫，分享海报

11-02 2461
05-27 1968
03-22 1251
©️2021 CSDN 皮肤主题: Age of Ai 设计师:meimeiellie

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。