Let's solve the problem that the array contains 0:
.
.
.
int product = 1;
int maxProduct = Integer.MIN_VALUE;
if ( m < 1) return 0;
for(int i = 0, len = a.length; i < len; i++ ) {
if (a[i] == 0) a[i] = 1; // solution
if (i < m) {
product *= a[i];
maxProduct = product;
} else {
product = product * a[i] / a[i - m];
maxProduct = maxProduct > product ? maxProduct : product;
}
}
return maxProduct;
But the array is a reference type, which will change the original array, so is there a better way? yes! we have :
.
.
.
int product = 1;
int maxProduct = Integer.MIN_VALUE;
if ( m < 1) return 0;
for(int i = 0, len = a.length; i < len; i++ ) {
int spi = a[i] == 0 ? 1 : a[i];
if (spi == 0) spi = 1;
if (i < m) {
product *= spi;
maxProduct = product;
} else {
int spi_m = a[i - m] == 0 ? 1 : a[i - m];
product = product * spi / spi_m;
maxProduct = maxProduct > product ? maxProduct : product;
}
}
return maxProduct;
Here is the original answer:
.
.
.
int product = 1;
int maxProduct = Integer.MIN_VALUE;
if ( m < 1) return 0;
for(int i = 0, len = a.length; i < len; i++ ) {
if (i < m) {
product *= a[i];
maxProduct = product;
} else {
product = product * a[i] / a[i - m];
maxProduct = maxProduct > product ? maxProduct : product;
}
}
return maxProduct;
an array like this:
1,2,3,4,5,6,7,10,8,9
if m is 3
so, in for loop:
- when i = 0, i = 1, i = 2 (i < 3 )
product *= a[i] =>
product = 1 * 1, product = 1 * 2 (now product is 2), product = 2 * 3 = 1 * 2 * 3 (m consecutive integers in the array)
maxProduct = 1, maxProduct = 2, maxProduct = 6
then i = 3,4,5,6,7,10,8,9 (i >= 3)
if i is 3
product = product * a[i] / a[i - m] = 1 * 2 * 3 * 4 / 1 = 2 * 3 * 4(m consecutive integers in the array)
product > maxProduct
so the maxProduct now is product
if i is 4
product = product * a[i] / a[i - m] = 2 * 3 * 4 * 5 / 2 = 3 * 4 * 5(m consecutive integers in the array)
product > maxProduct
so the maxProduct now is product
but when i > 8
product < maxProduct
maxProduct will still maxProduct not change
!!! english is hard!