Title Description:
Find the contiguous subarray within an array (containing at least one number) which have the largest product.
For example, given the array [2,3,-2,4] ,
The contiguous Subarray has the [2,3] largest product = 6 .
Subscribe to see which companies asked this question
That is: Given an array, the maximum continuous product is computed. For example: given [2,3,-2,4], the maximum product is 2*3 = 6 given [-2, 3,-4], the maximum product is -2*3*-4 Therefore, when encountering negative numbers, it is not easy to consider the smallest, if there are negative numbers, it will make the calculation error. The largest product at the end of number I is calculated as follows: 1. If number of I is greater than 0, then max[i] = max (Max[i-1]*nums[i], nums[i]) 2. If the number of I is less than 0, then max[i] = min (Min[i-1]*nums[i], nums[i]) so we need to record the maximum and minimum product at the end of number I. The minimum product at the end of number I is calculated as follows: 1. If Nums[i] is greater than 0, then min[i] = min (Min[i-1]*nums[i], nums[i]) 2. If Nums[i] is less than 0, then min[i] = max (Max[i-1]*nums[i], nums[i]) code is as follows:
1 classsolution (object):2 defmaxproduct (Self, nums):3 """4 : Type Nums:list[int]5 : Rtype:int6 """7ln =Len (nums)8MaxPro = [0]* (ln+1)9Minpro = [0]* (ln+1)TenMaxpro[0] = 1 OneMinpro[0] = 1 A forIinchRange (0, LN): - ifNums[i] >=0: -MAXPRO[I+1] = max (maxpro[i]*Nums[i], nums[i]) theMinpro[i+1] = min (minpro[i]*Nums[i], nums[i]) - Else: -Minpro[i+1] = min (maxpro[i]*Nums[i], nums[i]) -MAXPRO[I+1] = max (minpro[i]*Nums[i], nums[i]) + returnMax (maxpro[1:])
Leetcode's maximum Product subarray