买卖股票的最好时机 -- 每日一题07

'''
题目见:
https://www.nowcoder.com/practice/64b4262d4e6d4f6181cd45446a5821ec?tpId=196&tqId=37051&rp=1&ru=/exam/oj&qru=/exam/oj&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D196&difficulty=undefined&judgeStatus=undefined&tags=&title=
'''
'''
定义变量记录最小值和最大差值
每当有更小的最小值时,更新最小值
当前值减去最小值大于最大差值时,更新最差值
'''
class Solution:
    def maxProfit(self , prices: List[int]) -> int:
        if len(prices) <= 1:
            return 0
        the_min = prices[0]
        max = 0
        for i in range(1, len(prices)):
            if prices[i] < the_min:
                the_min = prices[i]
            else:
                max = max if max > prices[i]-the_min else prices[i]-the_min
        return max

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务