Topic:
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 .
test instructions and analysis: an array is given to find the largest sub-array of the Chuyang product. This problem can be solved using the dynamic programming method, I use two arrays posres and nonposres respectively to hold the largest positive product and the smallest negative product of the current element. The analysis shows that the maximum product of a subarray must be greater than or equal to 1 in the case of only one negative number. So for the i-1 element of the array nums[i-1], we can see that the maximum product of the current number may be three kinds:
(1) posres[i-1]*nums[i-1]>0, then the current maximum is posres[i-1]*nums[i-1], if less than 0, then the maximum negative value is posres[i-1]*nums[i-1]
(2) Nonposres[i-1]*nums[i-1]>0, then the current maximum is nonposres[i-1]*nums[i-1]; if it is greater than 0, then the maximum positive value is nonposres[i-1]*nums[i-1]
(3) Posres[i-1]*nums[i-1]==0 and nonposres[i-1]*nums[i-1]==0 alone, see the code
Then traverse the entire array, the time complexity is O (n), the spatial complexity is also O (n)
Code:
public class Solution {public int maxproduct (int[] nums) { int length=nums.length;if (length==1) return nums[0]; int[] Posres=new int[length+1];//record to the current point of the positive maximum product int[] Nonposres=new int[length+1];//record to the current point of the negative maximum product int max= Integer.min_value; Posres[0]=1; Nonposres[0]=1; for (int i=1;i<length+1;i++) { int a=posres[i-1]*nums[i-1]; int b=nonposres[i-1]*nums[i-1]; if (a>0) { posres[i]=a; } else if (a<0) nonposres[i]=a; if (b<0) nonposres[i]=b; else if (b>0) posres[i]=b; if (posres[i]==0&&nums[i-1]>=0) { posres[i]=nums[i-1]; } if (nonposres[i]==0&&nums[i-1]<=0) nonposres[i]=nums[i-1]; if (Posres[i]>max) max=posres[i]; } return max;} }
[Leetcode] 152. Maximum Product subarray Java