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.
最多只能买一只股票,使得收益最大。那就只需要维护一个从0到i当前股票最小值,然后和当前值做差得到当前最大收益,然后再和全局最大收益做max。
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if len(prices) < 2: return 0 ans = 0 min_current = prices[0] for i in range(1, len(prices), 1): ans = max(ans, prices[i] - min_current) min_current = min(min_current, prices[i]) return ans
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步