Maximum Product Subarray, Leetcode 解题笔记

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.

1. 如果当前值是正数,那么max = Math.max(A[i], A[i]*max)
2. 如果当前值是负数,那么max = Math.max(Math.max(A[i], A[i]*max), A[i]*min)

public class Solution {
    public int maxProduct(int[] A) {
        int curMax = A[0];
        int curMin = A[0];
        int totalMax = A[0];
        for(int i = 1; i < A.length; ++i){
            int curMax_copy = curMax;
            curMax = Math.max(Math.max(curMax*A[i], A[i]), curMin*A[i]);
            curMin = Math.min(Math.min(curMax_copy*A[i], A[i]), curMin*A[i]);
            totalMax = Math.max(curMax, totalMax);
        return totalMax;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s