1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| public class Solution { public int maxProduct(int[] A) { int max = A[0], length = A.length; int begin = 0, end, product; while (begin < length && A[begin] == 0) { begin++; } if (begin == length) return 0; end = begin + 1; product = A[begin]; while (end < length) { if (A[end] == 0) { max = Math.max(max, Math.max(0, countMax(begin, end, A, product))); begin = end + 1; while (begin < length && A[begin] == 0) { begin++; } if (begin == length) break; product = A[begin]; end = begin + 1; } else { product *= A[end++]; } } if (begin != length) max = Math.max(max, countMax(begin, length, A, product)); return max; }
private int countMax(int begin, int end, int[] A, int product) { if (product > 0 || end - begin == 1) { return product; } int index = begin; int preProduct = 1, sufProduct = 1; while (index < end - 1 && A[index] > 0) { preProduct *= A[index]; index++; } preProduct *= A[index]; index = end - 1; while (begin < index && A[index] > 0) { sufProduct *= A[index]; index--; } sufProduct *= A[index]; return Math.max(product / preProduct, product / sufProduct); } }
|