Leetcode152——Maximum Product Subarray

文章作者:Tyan
博客:noahsnail.com ?|? CSDN ?|? 簡書

1. 問題描述

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.

2. 求解

這個題跟Leetcode 53——Maximum Subarray類似,可以用三重循環(huán),兩種循環(huán)解決。但最好的還是用動態(tài)規(guī)劃解決,找出狀態(tài)轉移方程最關鍵。由于乘積可能為負數,負負得正,因此第i-1次的乘積最大值(maxValuePre)與最小值(minValuePre)都需要保留。當然也可以定義最大值最小值數組來保存第i次乘積的最大值(maxValue)與最小值(minValue)。與Maximum Subarray相比,最大值為maxValue = max(minValuePre * nums[i], maxValuePre * nums[i], nums[i]),最小值同樣如此。

沒有定義最大值數組與最小值數組

public class Solution {
    public int maxProduct(int[] nums) {
        int n = nums.length;
        int maxValue = nums[0];
        int minValue = nums[0];
        int result = nums[0];
        int maxValuePre = nums[0], minValuePre = nums[0];
        for(int i = 1; i < n; i++) {
            maxValue = Math.max(minValuePre * nums[i], Math.max(maxValuePre * nums[i], nums[i]));
            minValue = Math.min(minValuePre * nums[i], Math.min(maxValuePre * nums[i], nums[i]));
            if(maxValue > result) {
                result = maxValue;
            }
            maxValuePre = maxValue;
            minValuePre = minValue;
        }
        return result;
    }
}

定義最大值數組與最小值數組

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

推薦閱讀更多精彩內容