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.

求最值问题一般要考虑DP的解法,对于乘法,当前的连续乘积最大值有几种可能:
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;
    }
}
Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s