Here is the problem and the code (I was looking for solutions, and most of them are similar, one post is easy to read), my question is below two lines,
imax = max(A[i], imax * A[i]);
imin = min(A[i], imin * A[i]);
why we need to consider A [i] individually and why not just write how
imax = max(imin * A[i], imax * A[i]);
imin = min(imin * A[i], imax * A[i]);
Find a continuous subarak in the array (containing at least one number) that has the largest product.
For example, given the array [2,3, -2,4], the adjacent subarray [2,3] has the largest product = 6.
int maxProduct(int A[], int n) {
int r = A[0];
for (int i = 1, imax = r, imin = r; i < n; i++) {
if (A[i] < 0)
swap(imax, imin);
imax = max(A[i], imax * A[i]);
imin = min(A[i], imin * A[i]);
r = max(r, imax);
}
return r;
}
thanks in advance Lin
source
share