Thursday, November 20, 2014

Maximum

DP
but we only need two variables to store the maxvalue and minvalue

public int maxProduct(int[] A) {
        if (A.length == 1) return A[0];
        int maxProduct = A[0];
        int currMax = A[0];
        int currMin = A[0];
       
        for (int i=1; i<A.length; i++) {
            int temp = currMax;
            currMax = Math.max(Math.max(temp*A[i], A[i]), currMin*A[i]);
            currMin = Math.min(Math.min(currMin*A[i], A[i]), temp*A[i]);
            maxProduct = Math.max(maxProduct, currMax);
        }
        return maxProduct;
    }

No comments:

Post a Comment