121.買賣股票的最佳時機
'''
分治法:
一分爲2,最大收益要麼在前一半要麼在後一半
要麼跨中心:跨中心採用貪心策略:取前一半最小和後一半最大
迭代結束條件/邊界條件:
1.空集或只有1個元素
2.2個元素
由於分治法需要重複求解邊界條件,故此處使用動態規劃更爲適合
'''
n=len(prices)
if n<=1:
return 0
if n==2:
profit=prices[1]-prices[0]
if profit>0:
return profit
else:
return 0
mid=n//2
maxprofit_l=self.maxProfit(prices[0:mid])
maxprofit_r=self.maxProfit(prices[mid:n])
max_in=min(prices[0:mid])
max_out=max(prices[mid:n])
maxprofit_c=max_out-max_in
return max(maxprofit_c,maxprofit_l,maxprofit_r)
- 動態規劃——時間O(n),空間O(n)——》空間可化簡爲O(1)
'''
設dp[i]是到第i天的最大收益
默認dp[0]=0
dp[i]=max(dp[i-1],prices[i]-min(prices[0:i-1]))
要求記錄minprice
邊界條件:
1.序列爲空或僅有一個元素
'''
class Solution:
def maxProfit(self, prices: list) -> int:
n=len(prices)
if n<=1 or prices==sorted(prices,reverse=True):
return 0
mp=[0]
minprice=prices[0]
for i in range(1,n):
mp.append(max(mp[i-1],prices[i]-minprice))
if minprice>prices[i]:
minprice=prices[i]
return max(mp)
f=Solution()
l=[7,1,5,3,6,4]
f.maxProfit(l)