我最近解決了一個經典的 LeetCode 問題:「買賣股票的最佳時機」。這題要求你求出一次買賣股票所能獲得的最大利潤。讓我們深入探討我所探索過的不同方法及其複雜性。這是問題的 URL:
LeetCode 121
蠻力方法(時間複雜度:O(n^2))
最直接的解決方案可能是將陣列中的每個元素與所有剩餘元素進行比較。對於每個價格,我們計算如果在稍後的一天出售它會產生的利潤。然後我們追蹤遇到的最大利潤。然而,這種方法的時間複雜度較高,導致 Time Limit Exceeded。
/** * @param {number[]} prices * @return {number} */ var maxProfit = function (prices) { let max = 0; for (var i = 0; i a) return b - a; else return 0; }
原因如下: 我們將每個元素與 n-1 個其他元素進行比較,從而產生 n*(n-1)/2 次比較。這大致相當於 O(n^2) 時間複雜度,對於大型資料集來說效率很低。不幸的是,這種方法經常會導致 LeetCode 出現「Time Limit Exceeded」錯誤。
二指標法(時間複雜度:O(n))
為了提高效率,我們可以利用先買後賣的事實。我們可以引入兩個指標:
- 購買:指向當前的潛在購買價格。
- sell:指向候選售價。
這個想法是從第三個元素開始迭代價格數組(因為前兩個元素用於買賣)。我們不斷檢查賣出價(當前元素)和買入價之間的差額是否大於當前最大利潤。如果為真,我們更新最大利潤。否則,我們將買入指標更新為當前元素(可能是較低的買入價格)並將賣出指標向前移動一步。
這種方法顯著提高了時間複雜度,達到了 O(n),因為我們只迭代數組一次。
/** * @param {number[]} prices * @return {number} */ var maxProfit = function (prices) { let maxProfit = 0; let buy = 0; let sell = 1; while (sell <p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172284027594031.png?x-oss-process=image/resize,p_40" class="lazy" alt="LeetCode 問題:買賣股票的最佳時機" loading="lazy" style="max-width:90%" style="max-width:90%"></p> <h2> 貪婪方法(時間複雜度:O(n))與 Python 範例 </h2> <p>我們可以透過貪心方法實現類似的時間複雜度。這裡的關鍵是要明白,只有低買高賣才能達到最大利潤。 因此,我們可以迭代價格數組並追蹤迄今為止遇到的最低價格。這代表了潛在的購買價格。 </p> <p>這是貪婪方法的 Python 實作:<br> </p> <pre class="brush:php;toolbar:false">class Solution: def maxProfit(self, prices: List[int]) -> int: max_profit = 0; min_buy = float('inf') for price in prices: min_buy = min(min_buy , price ) max_profit = max(max_profit, price-min_buy) return max_profit
您可以隨時了解更多有關在我的作品集上還可以在哪裡找到我的信息
以上是LeetCode 問題:買賣股票的最佳時機的詳細內容。更多資訊請關注PHP中文網其他相關文章!

pythonuseshybridapprace,ComminingCompilationTobyTecoDeAndInterpretation.1)codeiscompiledtoplatform-Indepententbybytecode.2)bytecodeisisterpretedbybythepbybythepythonvirtualmachine,增強效率和通用性。

theKeyDifferencesBetnewpython's“ for”和“ for”和“ loopsare:1)” for“ loopsareIdealForiteringSequenceSquencesSorkNowniterations,而2)”,而“ loopsareBetterforConterContinuingUntilacTientInditionIntionismetismetistismetistwithOutpredefinedInedIterations.un

在Python中,可以通過多種方法連接列表並管理重複元素:1)使用 運算符或extend()方法可以保留所有重複元素;2)轉換為集合再轉回列表可以去除所有重複元素,但會丟失原有順序;3)使用循環或列表推導式結合集合可以去除重複元素並保持原有順序。

fasteStmethodMethodMethodConcatenationInpythondependersonListsize:1)forsmalllists,operatorseffited.2)forlargerlists,list.extend.extend()orlistComprechensionfaster,withextendEffaster,withExtendEffers,withextend()withextend()是extextend()asmoremory-ememory-emmoremory-emmoremory-emmodifyinginglistsin-place-place-place。

toInSerteLementIntoApythonList,useAppend()toaddtotheend,insert()foreSpificPosition,andextend()formultiplelements.1)useappend()foraddingsingleitemstotheend.2)useAddingsingLeitemStotheend.2)useeapecificindex,toadapecificindex,toadaSpecificIndex,toadaSpecificIndex,blyit'ssssssslorist.3 toaddextext.3

pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)他們areStoredIncoNtiguulMemoryBlocks,mayrequireRealLealLocationWhenAppendingItems,EmpactingPerformance.2)LinkesedlistSwoldOfferefeRefeRefeRefeRefficeInsertions/DeletionsButslowerIndexeDexedAccess,Lestpypytypypytypypytypy

pythonoffersFourmainMethodStoreMoveElement Fromalist:1)刪除(值)emovesthefirstoccurrenceofavalue,2)pop(index)emovesanderturnsanelementataSpecifiedIndex,3)delstatementremoveselemsbybybyselementbybyindexorslicebybyindexorslice,and 4)

toresolvea“ dermissionded”錯誤Whenrunningascript,跟隨台詞:1)CheckAndAdjustTheScript'Spermissions ofchmod xmyscript.shtomakeitexecutable.2)nesureThEseRethEserethescriptistriptocriptibationalocatiforecationAdirectorywherewhereyOuhaveWritePerMissionsyOuhaveWritePermissionsyYouHaveWritePermissions,susteSyAsyOURHomeRecretectory。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Atom編輯器mac版下載
最受歡迎的的開源編輯器

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

SublimeText3漢化版
中文版,非常好用

SublimeText3 Linux新版
SublimeText3 Linux最新版

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器