class Solution {
public:
    //和最大子串和不同的是:需要同时记录最大的正数和最小的负数
    int maxProduct(int A[], int n) {
        if(n==0) return 0;
        if(n==1) return A[0]; //这一句不能少,否则在就输出maxVal=0
        int maxPosValEndsWithLast = 0;
        int minNegValEndsWithLast = 0;
        int maxVal=0;
        int minVal=0;
        for(int i=0;i<n;i++){
            if(A[i]>0){
                maxPosValEndsWithLast = max( maxPosValEndsWithLast*A[i], A[i]);
                minNegValEndsWithLast = min( minNegValEndsWithLast*A[i], A[i]);
            }else if(A[i]<0){
                int temp = maxPosValEndsWithLast; //注意保存临时现场
                maxPosValEndsWithLast = minNegValEndsWithLast*A[i];
                minNegValEndsWithLast = min( temp*A[i], A[i]);
            }else{//A[i]==0
                maxPosValEndsWithLast = 0;
                minNegValEndsWithLast = 0;
            }

            //update
            maxVal = max(maxVal,maxPosValEndsWithLast);
            minVal = min(minVal,minNegValEndsWithLast);
        }
        return maxVal;
    }
};

RioDream
126 声望14 粉丝