2019-08-21LeetCode121. 买卖股票的最佳时机

10min,最大连续子序列和

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        min_,max_=100000000,0 # 这里赋值为0而不能-1,是因为特殊情况
        for i in range(0,len(prices)): #这里不能从1开始
            min_=min(min_,prices[i])
            if prices[i]>min_:
                max_=max(max_,prices[i]-min_)
        return max_

15min,状态机
初始化的时候注意-无穷和0,max 取-
https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iii/solution/yi-ge-tong-yong-fang-fa-tuan-mie-6-dao-gu-piao-wen/

class Solution2:
    def maxProfit(self, prices: List[int]) -> int:
        if not prices:return 0
        dpi0,dpi1=0,-prices[0]
        for i in range(1,len(prices)):
            dpi0=max(dpi0,dpi1+prices[i])
            dpi1=max(dpi1,-prices[i])
        return dpi0
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容