Sunday, January 11, 2015

LeetCode 152: Maximum Product Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.
public class Solution {
    public int maxProduct(int[] A) {
        // Similar to "Maximum Subarray" but more complicated.
        int n = A.length;
        
        if (n == 0)
            return 0;
            
        if (n == 1)
            return A[0];
            
        // Note: currentMin*A[i] may become currentMax (neg*neg = positive)
        // Simiarly, currentMax*A[i] may become currentMin
        int currentMax = A[0];
        int currentMin = A[0];
        int max = A[0];
        
        for (int i = 1; i < n; i++)
        {
            int previousMax = currentMax;
            currentMax = Math.max(Math.max(currentMax*A[i], A[i]), currentMin*A[i]);
            currentMin = Math.min(Math.min(currentMin*A[i], A[i]), previousMax*A[i]);
            max = Math.max(max, currentMax);
        }
        
        return max;
    }
}

No comments:

Post a Comment