121. Best Time to Buy and Sell Stock
Say you have an array for which the ith element is the price of a given stock on day i.If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Note that you cannot sell a stock before you buy one.
Example:
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.
Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0.
Solution:
class Solution: def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ buy = float("inf") max_profile = 0 for price in prices: buy = min(buy, price) max_profile = max(max_profile, price-buy) return max_profile
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://specialneedsforspecialkids.com/yun/42033.html
摘要:求可能的最大利潤(rùn)題目給了兩個(gè)例子最大利潤(rùn)就是進(jìn)價(jià)為,賣(mài)價(jià)為的時(shí)候,利潤(rùn)為在這個(gè)案例中,進(jìn)價(jià)一直高于售價(jià),所以無(wú)法成交,返回。主要注意一下,先買(mǎi)入才能賣(mài)出賣(mài)價(jià)一定要比買(mǎi)入價(jià)格高才能成交就可以了。 題目詳情 Say you have an array for which the ith element is the price of a given stock on day i.If yo...
摘要:分析因?yàn)楫?dāng)前日期買(mǎi)賣(mài)股票會(huì)受到之前日期買(mǎi)賣(mài)股票行為的影響,首先考慮到用解決。所以我們可以用兩個(gè)數(shù)組分別記錄當(dāng)前持股跟未持股的狀態(tài)。 Best Time to Buy and Sell Stock with Cooldown Say you have an array for which the ith element is the price of a given stock on ...
摘要:題目鏈接來(lái)解,要用兩個(gè)分別表示現(xiàn)在的操作是還是,優(yōu)化空間用滾動(dòng)數(shù)組,或者幾個(gè) 309. Best Time to Buy and Sell Stock with Cooldown 題目鏈接:https://leetcode.com/problems... dp來(lái)解,要用兩個(gè)dp array分別表示現(xiàn)在的操作是buy還是sell,優(yōu)化空間用滾動(dòng)數(shù)組,或者幾個(gè)int public clas...
摘要:示例輸入輸出解釋對(duì)應(yīng)的交易狀態(tài)為買(mǎi)入賣(mài)出冷凍期買(mǎi)入賣(mài)出思路這道題使用動(dòng)態(tài)規(guī)劃。狀態(tài)表示當(dāng)天休息能夠獲得的最大價(jià)值,表示當(dāng)天持有股票能夠獲得的最大價(jià)值,表示當(dāng)天持有股票能夠獲得的最大價(jià)值。 Description Say you have an array for which the ith element is the price of a given stock on day i. ...
摘要:關(guān)鍵字,,算法,,動(dòng)態(tài)規(guī)劃,上關(guān)于主題的題目有四個(gè)這四個(gè)題目難度依次遞增。其中第四個(gè)問(wèn)題是尋求一個(gè)通解,在給定和最大買(mǎi)賣(mài)次數(shù)的情況下,求最大收益。首先大致的解題方向是動(dòng)態(tài)規(guī)劃,這個(gè)應(yīng)該不難想到。之后就是怎么找到狀態(tài),怎么列狀態(tài)轉(zhuǎn)移方程。 關(guān)鍵字:leetcode,Best Time To Buy And Sell Stock,算法,algorithm,動(dòng)態(tài)規(guī)劃,dynamic prog...
閱讀 3514·2023-04-25 20:09
閱讀 3720·2022-06-28 19:00
閱讀 3035·2022-06-28 19:00
閱讀 3058·2022-06-28 19:00
閱讀 3132·2022-06-28 19:00
閱讀 2859·2022-06-28 19:00
閱讀 3014·2022-06-28 19:00
閱讀 2610·2022-06-28 19:00