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
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://m.specialneedsforspecialkids.com/yun/42033.html
摘要:求可能的最大利潤題目給了兩個例子最大利潤就是進價為,賣價為的時候,利潤為在這個案例中,進價一直高于售價,所以無法成交,返回。主要注意一下,先買入才能賣出賣價一定要比買入價格高才能成交就可以了。 題目詳情 Say you have an array for which the ith element is the price of a given stock on day i.If yo...
摘要:分析因為當前日期買賣股票會受到之前日期買賣股票行為的影響,首先考慮到用解決。所以我們可以用兩個數組分別記錄當前持股跟未持股的狀態。 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 ...
摘要:題目鏈接來解,要用兩個分別表示現在的操作是還是,優化空間用滾動數組,或者幾個 309. Best Time to Buy and Sell Stock with Cooldown 題目鏈接:https://leetcode.com/problems... dp來解,要用兩個dp array分別表示現在的操作是buy還是sell,優化空間用滾動數組,或者幾個int public clas...
摘要:示例輸入輸出解釋對應的交易狀態為買入賣出冷凍期買入賣出思路這道題使用動態規劃。狀態表示當天休息能夠獲得的最大價值,表示當天持有股票能夠獲得的最大價值,表示當天持有股票能夠獲得的最大價值。 Description Say you have an array for which the ith element is the price of a given stock on day i. ...
摘要:關鍵字,,算法,,動態規劃,上關于主題的題目有四個這四個題目難度依次遞增。其中第四個問題是尋求一個通解,在給定和最大買賣次數的情況下,求最大收益。首先大致的解題方向是動態規劃,這個應該不難想到。之后就是怎么找到狀態,怎么列狀態轉移方程。 關鍵字:leetcode,Best Time To Buy And Sell Stock,算法,algorithm,動態規劃,dynamic prog...
閱讀 3532·2023-04-25 20:09
閱讀 3736·2022-06-28 19:00
閱讀 3056·2022-06-28 19:00
閱讀 3075·2022-06-28 19:00
閱讀 3168·2022-06-28 19:00
閱讀 2874·2022-06-28 19:00
閱讀 3038·2022-06-28 19:00
閱讀 2632·2022-06-28 19:00