題目:給定一個數組,它的第 i 個元素是一支給定股票第 i 天的價格。 如果你最多只允許完成一筆交易(即買入和賣出一支股票一次),設計一個算法來計算你所能獲取的最大利潤。 注意:你不能在買入股票前賣出股票。
思路:動態規划(最佳),還可以用暴力
在某教育科技公司面試時遇到過。
程序1:動態規划
class Solution:
def maxProfit(self, prices: List[int]) -> int:
length = len(prices)
if length <= 1:
return 0
buy = prices[0]
auxiliary = [0] * length
for index in range(1, length):
auxiliary[index] = max(auxiliary[index - 1], prices[index] - buy)
buy = min(buy, prices[index])
result = max(auxiliary)
return result
程序2:暴力
class Solution:
def maxProfit(self, prices: List[int]) -> int:
length = len(prices)
if length <= 1:
return 0
if length == 2:
if prices[0] >= prices[1]:
return 0
else:
return prices[1] - prices[0]
#Find the buy point
index1 = 1
auxiliary_buy = []
auxiliary_buy.append(prices[1])
auxiliary_sell = []
auxiliary_sell.append(prices[length - 1])
while index1 < length:
if prices[index1] < prices[index1 - 1]:
auxiliary_buy.append(prices[index1])
buy = min(auxiliary_buy)
#Find the sell point
auxiliary_sell.append(max(prices[index1 : ]))
sell = max(auxiliary_sell)
result = sell - buy
if result <= 0:
return 0
break
index1 += 1
return result