#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @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



京公网安备 11010502036488号