python买卖股票_Python实现买卖股票的最佳时机的一种方法
給定一個數組,該數組中第i個元素是某個股票第i天的價錢
如果最多只能完成一次交易(買入股票,賣出股票),設計一個算法,可以獲得最大的利潤
注意:在你買入股票之前不能賣出股票
Example 1:
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Not 7-1 = 6, as selling price needs to be larger than buying price.
Example 2:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
1:申明三個變量,頭指針pre、尾指針tail和最大利潤maxProfit,頭指針指向當前訪問到的數組的最小值,尾指針指向當前訪問到的最大值
訪問數組prices,如果出現i-pre
繼續訪問數組,如果出現i-pre>tail-pre就替換tail為i(i元素值必定大于尾指針tail值),并且替換maxProfit的值為max(maxProfit,i-pre)
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices)<=1:
return 0
pre = prices[0]
tail = prices[0]
maxProfit = 0
for i in range(1,len(prices)): #從第二個元素開始訪問數組
if prices[i]-pre<0: #替換頭指針和尾指針為當前訪問到的數組的最小值
pre = prices[i]
tail = prices[i]
if prices[i]-pre>tail-pre: #替換尾指針為當前訪問(從最小數值開始)的最大值
maxProfit = max(prices[i]-pre, maxProfit) #對比此時利潤和之前保存的最大利潤,返回現階段可獲得的最大利潤
tail = prices[i]
return maxProfit
2:暴力法O(n^2),錯誤:超出時間限制
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
maxProfit = 0
for i in range(len(prices)):
for j in range(i+1,len(prices)):
if prices[j]-prices[i]>maxProfit:
maxProfit = prices[j]-prices[i]
return maxProfit
算法題來自:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/description/
總結
以上是生活随笔為你收集整理的python买卖股票_Python实现买卖股票的最佳时机的一种方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: wps插入入html,WPS文字技巧—如
- 下一篇: 新塘单片机烧写器_ICP Program