Simple O(n) Solution with O(1) Space


#1
int Solution::maxProduct(const vector<int> &A) {
    int ans=*max_element(A.begin(),A.end());
    int n=A.size(),prev_min=A[0],prev_max=A[0],curr_min,curr_max;
    for(int i=1;i<n;i++)
    {
        int t1=A[i]*prev_min,t2=A[i]*prev_max;
        curr_min=min({A[i],t1,t2});
        curr_max=max({A[i],t1,t2});
        ans=max({ans,curr_max,curr_min});
        prev_min=curr_min;
        prev_max=curr_max;
    }
    return ans;
}