简体   繁体   中英

Find maximum product subarray

We need to Find the contiguous subarray within an array (containing at least one number) which has the largest product and return an integer corresponding to the maximum product possible. I found this code to solve the same:

int maxProduct(const vector<int> &A)
{
    int n = A.size();
    vector<int> maxarray(n);
    vector<int> minarray(n);
    maxarray[0] = A[0];
    minarray[0] = A[0];
    int result = A[0];
    for(int i=1;i<n;i++){
        if(A[i]>0){
            maxarray[i] = max(A[i],maxarray[i-1]*A[i]);
            minarray[i] = min(A[i],minarray[i-1]*A[i]);
        }else{
            maxarray[i] = max(A[i],minarray[i-1]*A[i]);
            minarray[i] = min(A[i],maxarray[i-1]*A[i]);
        }
        result = max(result,maxarray[i]);
    }

    return result;
}

What is the need to maintain a minarray? And can you please explain these lines:

if(A[i]>0){
            maxarray[i] = max(A[i],maxarray[i-1]*A[i]);
            minarray[i] = min(A[i],minarray[i-1]*A[i]);
        }else{
            maxarray[i] = max(A[i],minarray[i-1]*A[i]);
            minarray[i] = min(A[i],maxarray[i-1]*A[i]);
        }

Why are we updating the maxarray and minarray as done in the above lines of code?

minarray 's purpose is to handle negative numbers.

{-1, 42, -2} would return 42 without minarray .

if (A[i]>0){
    maxarray[i] = max(A[i], maxarray[i-1]*A[i]);
    minarray[i] = min(A[i], minarray[i-1]*A[i]);
} else {
    maxarray[i] = max(A[i], minarray[i-1]*A[i]);
    minarray[i] = min(A[i], maxarray[i-1]*A[i]);
}

When A[i] is positive, prev*A[i] doesn't change of sign. Other case to handle: when previous value is 0

So maximum product until index i is

  • A[i] if maxarray[i-1] is 0 (or negative with initialization)
  • maxarray[i-1]*A[i] else.

std::max simplifies the condition.

In the same way, minimum product (largest negative number) would be std::min(A[i], minarray[i-1] * A[i]) .

When A[i] is negative, prev*A[i] does change of sign. so maximum has to take previous minimum

maxarray[i] = max(A[i], minarray[i-1] * A[i]); .

When A[i] == 0 , both maximum and minimum would be 0 . (both branch would be fine for it).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM