Here is the problem and code (I searched for solutions and most are similar, post one easy to read), my question is for 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 as,
imax = max(imin * A[i], imax * A[i]);
imin = min(imin * A[i], imax * A[i]);
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4], the contiguous subarray [2,3] has the largest product = 6.
int maxProduct(int A[], int n) {
// store the result that is the max we have found so far
int r = A[0];
// imax/imin stores the max/min product of
// subarray that ends with the current number A[i]
for (int i = 1, imax = r, imin = r; i < n; i++) {
// multiplied by a negative makes big number smaller, small number bigger
// so we redefine the extremums by swapping them
if (A[i] < 0)
swap(imax, imin);
// max/min product for the current number is either the current number itself
// or the max/min by the previous number times the current one
imax = max(A[i], imax * A[i]);
imin = min(A[i], imin * A[i]);
// the newly computed max value is a candidate for our global result
r = max(r, imax);
}
return r;
}
thanks in advance, Lin
imaxandiminboth start life equal tor, your update proposal would keep the two values always equal. Not what you want. (You are aware, I hope, that the code you posted finds the largest product, not subarray itself--as required in the problem statement).