[LeetCode] 152. Maximum Product Subarray 求最大子數(shù)組乘積

Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.

Example 1:

<pre class="highlighter-hljs" highlighted="true" has-selection="true" style="margin: 10px auto; padding: 0px; transition-duration: 0.2s; transition-property: background, font-size, border-color, border-radius, border-width, padding, margin, color; overflow: auto; color: rgb(73, 73, 73); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
</pre>

Example 2:

<pre style="margin: 10px auto; padding: 0px; transition-duration: 0.2s; transition-property: background, font-size, border-color, border-radius, border-width, padding, margin, color; overflow: auto; color: rgb(73, 73, 73); font-size: 14px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.</pre>
思路:
一開始的暴力解法,找出所有的子數(shù)組,算出乘積,然后找出比較大的一個(gè)。但是復(fù)雜度是n2;換思路,dp來做,要用兩個(gè)dp數(shù)組。其中f[i]表示[0,i]范圍內(nèi)并且包含nums[i]的最大子數(shù)組乘積。g[i]標(biāo)識[0,i]范圍內(nèi)并且包含nums[i]的最小子數(shù)組乘積。初始化時(shí)f[0]和g[0]都是nums[0];name從數(shù)組的第二個(gè)數(shù)字開始遍歷,此時(shí)數(shù)組的最大值和最小值置灰在這三個(gè)數(shù)字之間產(chǎn)生,即f[i-1]nums[i];nums[i];g[i-1]nums[i]。所以用這三者中的最大值來更新f[i],用最小值來更新g[i],然后用f[i]來更新res即可。

/**
 * @param {number[]} nums
 * @return {number}
 */
var maxProduct = function(nums) {
    var max = nums[0];
    var min = nums[0];
    var res = nums[0];
    for(var i = 1; i< nums.length; i++) {
        var mx = max;
        var nx = min;
        max = Math.max(mx*nums[i], nums[i], nx*nums[i]);
        min = Math.min(mx*nums[i], nums[i], nx*nums[i]);
        res = Math.max(max, res);
    }
    return res;
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容