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 [2,3] have the largest product = 6.
Analysis:
There are two main considerations here: 1, the number of negative numbers between the head element and the first 0 elements and two 0 elements; 2. The current maximum value should be recalculated when 0 o'clock is encountered
The idea of design:
1, the subject for more convenient, I use the extra space, and the space complexity of O (n)
2. The first array is primarily used to calculate the value multiplied from the beginning or from 0, and the second array is used to calculate the product of each element starting with the first negative number from the beginning or the 0.
Example: (The above may not explain too clearly because of bad expression)
Original sequence:
Onevalue:
|
2 |
4 |
-4 |
-12 |
-48 |
0 |
2 |
-2 |
-6 |
6 |
Twovalue:
Code:
PackageCom.edu.leetcode;Importjavax.xml.transform.Templates; Public classMaximumproductsubarray { Public intMaxproducts (int[] A) {if(a.length==1) {//if only one element in the array is output directly returnA[0]; } int[] Onevalues =New int[A.length];//secondary space 1, which records the product from the beginning or from 0 to the current position int[] twovalues=New int[A.length];//Secondary Space 2, when the first negative number is encountered from the beginning or from 0, the subsequent value starts again from the current positionOnevalues[0]=a[0]; twovalues[0]=a[0]; BooleanFirst =true;//start from scratch or 0 to determine if a negative number is encountered for(inti=1;i<a.length;i++){ if(onevalues[i-1]==0) {Onevalues[i]=A[i]; Twovalues[i]=A[i]; First=true; } Else{ if(A[i-1]<=-1&&first) {//assigns the value of twovalues[i] to a[i when one of the preceding numbers is the first negative number from the beginning or from 0twovalues[i]=A[i]; Onevalues[i]=onevalues[i-1]*A[i]; First=false; } Else{Onevalues[i]=onevalues[i-1]*A[i]; Twovalues[i]=twovalues[i-1]*A[i]; } } } intMaxvalue=onevalues[0]; for(inti=0;i<onevalues.length;i++){ if(onevalues[i]>maxValue) MaxValue=Onevalues[i]; if(twovalues[i]>maxValue) MaxValue=Twovalues[i]; } returnMaxValue; } Public Static voidMain (string[] args) {//TODO auto-generated Method StubMaximumproductsubarray MPs =NewMaximumproductsubarray (); int[] s = {2,3,-1}; System.out.println (Mps.maxproducts (s)); }}
Maximum Product subarray Java implementation