Share my simple C++ code: O(n) time one-pass, O(1) space


  • 0
    S

    localmin and localmax store the minimum prod and max prod that contains current element

    class Solution {
    public:
        int maxProduct(int A[], int n) {
            int localmin = 0;
            int localmax = 0;
            int globalmax = 0;
            
            if(n == 0) return 0;
            if(n == 1) return A[0];
            
            for(int i = 0; i < n; i++) {
                int tmplocalmin = localmin;
                localmin = min(min(A[i], A[i] * localmin), A[i] * localmax);
                localmax = max(max(A[i], A[i] * tmplocalmin), A[i] * localmax);
                
                if(localmax > globalmax) globalmax = localmax;
            }
            
            return globalmax;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.