给定一个double类型的数组arr,其中的元素可正可负可0,返回连续子数组累乘的最大乘积。
数据范围:数组大小满足 ,数组中元素满足
进阶:空间复杂度 ,时间复杂度
[-2.5,4,0,3,0.5,8,-1]
12.00000
取连续子数组[3,0.5,8]可得累乘的最大乘积为12.00000
[1.0,0.0,0.0]
1.00000
取连续子数组[1.0]可得累乘的最大乘积为1.00000
class Solution: def maxProduct(self , nums: List[float]) -> float: # write code here dp_max=[1]*len(nums) dp_max[0]=nums[0] dp_min=[1]*len(nums) dp_min[0]=nums[0] for i in range(1,len(nums)): dp_max[i]=max(nums[i],dp_min[i-1]*nums[i],dp_max[i-1]*nums[i]) dp_min[i]=min(nums[i],dp_max[i-1]*nums[i],dp_min[i-1]*nums[i]) return max(max(dp_max),max(dp_min))
class Solution: def maxProduct(self , arr ): # write code here if not arr: return 0 ans = arr[0] maxnum = arr[0] minnum = arr[0] for i in range(1, len(arr)): m, n = maxnum, minnum maxnum = max(m*arr[i], n*arr[i], arr[i]) minnum = min(m*arr[i], n*arr[i], arr[i]) ans = max(ans, maxnum) return ans