日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python买卖股票_Python实现买卖股票的最佳时机的一种方法

發布時間:2023/12/20 python 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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实现买卖股票的最佳时机的一种方法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。