【leetcode】Python實現-121.買賣股票的最佳時機
阿新 • • 發佈:2018-12-24
121.買賣股票的最佳時機
描述
給定一個數組,它的第 i 個元素是一支給定股票第 i 天的價格。
如果你最多隻允許完成一筆交易(即買入和賣出一支股票),設計一個演算法來計算你所能獲取的最大利潤。
注意你不能在買入股票前賣出股票。
示例1
輸入: [7,1,5,3,6,4]
輸出: 5
解釋: 在第 2 天(股票價格 = 1)的時候買入,在第 5 天(股票價格 = 6)的時候賣出,最大利潤 = 6-1 = 5 。
注意利潤不能是 7-1 = 6, 因為賣出價格需要大於買入價格。
示例2
輸入: [7,6,4,3,1]
輸出: 0
解釋: 在這種情況下, 沒有交易完成, 所以最大利潤為 0。
我
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
l = []
for i in range(len(prices)):
for j in range(i+1, len(prices)):
if prices[j] > prices[i]:
l.append(prices[j]-prices[i])
if not l:
return 0
else:
return max(l)
果不其然,超出時間限制。兩層迴圈
然後修改了程式碼,表面上看只有一層迴圈,但事實上本質還是兩層迴圈。雖然比第一版本的執行時間要快一點,但是依然超出時間限制。
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
l = []
for i in range(len(prices)-1):
j = max(prices[i+1:])
if j > prices[i]:
l.append(j-prices[i])
if not l:
return 0
else:
return max(l)
看看別人的思路。在價格最低的時候買入,差價最大的時候賣出就解決了!沒毛病這個方案,跟實際買賣很像,然而真的炒股的時候我們並不能預測每一天的價格。
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) < 2:
return 0
profit = 0
minimum = prices[0]
for i in prices:
minimum = min(i, minimum)
profit = max(i - minimum, profit)
return profit
一次迴圈搞定查詢最小值和最大差值。