Maximum Product SubarrayTotal Accepted:
16617 Total Submissions:
96901
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 .
Analysis
Besides keeping track of the largest product, we also need to keep track of the smallest product.
Records the current maximum, minimum value. Because a negative number is encountered, the product with the minimum value may become the maximum value.
[Precautions]
Note the handling of the 0 value.
[CODE]
public class Solution {public int maxproduct (int[] A) { if (A==null | | A.LENGTH<1) return 0; if (A.length < 2) return a[0]; int global = a[0]; int max = A[0], min = a[0]; for (int i=1; i<a.length; i++) { int A = max*a[i]; int b = Min*a[i]; max = Math.max (A[i], Math.max (A, b)); min = Math.min (A[i], math.min (A, b)); Global = Math.max (max, Global); } return global; }}
Leetcode 152:maximum Product Subarray