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.

一刷
題解:求最大乘積子數組。 依然是用Dynamic Programming的思想,不過這回我們要維護一個max以及一個min。注意,當當前num[i]為負數時,max和min交換。
Time Complexity - O(n), Space Complexity - O(1)。

public class Solution {
    public int maxProduct(int[] nums) {
        if(nums == null || nums.length == 0)
            return 0;
        int res = nums[0], max = nums[0], min = nums[0];
        
        for(int i = 1; i < nums.length; i++) {
            if(nums[i] > 0) {
                max = Math.max(nums[i], nums[i] * max);
                min = Math.min(nums[i], nums[i] * min);
            } else {
                int max_copy = max;
                max = Math.max(nums[i], nums[i] * min);
                min = Math.min(nums[i], nums[i] * max_copy);
            }
            res = Math.max(res,max);
        }
        
        return res;
    }
}

二刷
首先思考,當長度增1,是不是可以利用之前的解,如果可以的話,就是DP問題。
之前的解,最大值和最小值都要保存下來,因為如果當前是負數,那么最大值就變成了最小值。

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

推薦閱讀更多精彩內容