题解 | 连续子数组的最大乘积

连续子数组的最大乘积

https://www.nowcoder.com/practice/abbec6a3779940aab2cc564b22d36859

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param nums int整型一维数组 
# @return int整型
#
class Solution:
    def maxProduct(self , nums: List[int]) -> int:
        # write code here
        if not nums:#数组为空,直接返回0
            return 0
        ans = max_x = min_x = nums[0]#最大值,当前累乘最大值,当前累乘最小值
        for x in nums[1:]:
            if x<0:#负数会导致最大、最小发生变化
                max_x, min_x = min_x, max_x
            max_x = max(x,max_x*x)#当前最大值更新
            min_x = min(x,min_x*x)#当前最小值更新
            ans = max(ans,max_x)#累计最大值更新
        return ans

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务