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.

Solution:DP

思路:
Time Complexity: O(N) Space Complexity: O(1)

Solution Code:

class Solution {
    public int maxProduct(int[] nums) {
        int g_max = nums[0];
        int c_max = nums[0];
        int c_min = nums[0];
        
        for(int i = 1; i < nums.length; i++) {
            int new_c_max = Math.max(Math.max(nums[i], nums[i] * c_max), nums[i] * c_min); 
            int new_c_min = Math.min(Math.min(nums[i], nums[i] * c_max), nums[i] * c_min); 
            g_max = Math.max(g_max, new_c_max);
            c_max = new_c_max;
            c_min = new_c_min;
        }
        
        return g_max; 
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容