[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:

發佈了194 篇原創文章 · 獲贊 4 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章