天天看點

[Leetcode 152, Medium] Maximum Product Subarray

Problem:

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

.

Analysis:

Solutions:

C++:

int maxProduct(vector<int>& nums) 
    {
        int g_max = nums[0];
        int l_min = nums[0];
        int l_max = nums[0] > 0? nums[0] : 1;
        for(int i = 1; i < nums.size(); ++i) {
            int new_l_max = nums[i] * l_max;
            int new_l_min = nums[i] * l_min;
            l_max = max(max(new_l_max, new_l_min), nums[i]);
            l_min = min(min(new_l_max, new_l_min), nums[i]);
            g_max = max(g_max, max(l_max, l_min));
        }

        return g_max;
    }
           

Java :

Python: