dp-leetcode152

動態規劃問題,存在重疊子問題




/**
 * <p>給你一個整數數組 <code>nums</code>&nbsp;,請你找出數組中乘積最大的非空連續子數組(該子數組中至少包含一個數字),並返回該子數組所對應的乘積。</p>
 *
 * <p>測試用例的答案是一個&nbsp;<strong>32-位</strong> 整數。</p>
 *
 * <p><strong>子數組</strong> 是數組的連續子序列。</p>
 *
 * <p>&nbsp;</p>
 *
 * <p><strong>示例 1:</strong></p>
 *
 * <pre>
 * <strong>輸入:</strong> nums = [2,3,-2,4]
 * <strong>輸出:</strong> <code>6</code>
 * <strong>解釋:</strong>&nbsp;子數組 [2,3] 有最大乘積 6。
 * </pre>
 *
 * <p><strong>示例 2:</strong></p>
 *
 * <pre>
 * <strong>輸入:</strong> nums = [-2,0,-1]
 * <strong>輸出:</strong> 0
 * <strong>解釋:</strong>&nbsp;結果不能爲 2, 因爲 [-2,-1] 不是子數組。</pre>
 *
 * <p>&nbsp;</p>
 *
 * <p><strong>提示:</strong></p>
 *
 * <ul>
 * <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li>
 * <li><code>-10 &lt;= nums[i] &lt;= 10</code></li>
 * <li><code>nums</code> 的任何前綴或後綴的乘積都 <strong>保證</strong>&nbsp;是一個 <strong>32-位</strong> 整數</li>
 * </ul>
 * <div><div>Related Topics</div><div><li>數組</li><li>動態規劃</li></div></div><br><div><li>👍 1838</li><li>👎 0</li></div>
 */

//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public int maxProduct(int[] nums) {
        if (nums.length == 0) {
            return 0;
        }

        int n = nums.length;
        int[] dpMax = new int[n + 1];
        int[] dpMin = new int[n + 1];
        dpMax[0] = nums[0];
        dpMin[0] = nums[0];
        int res = dpMax[0];


        for (int i = 1; i < n; i++) {
            // 考慮情況 5,6,-3,4,-3 這個情況,所以遞推方程要考慮 負數,也就是最小值問題
            dpMax[i] = Math.max(dpMax[i - 1] * nums[i], Math.max(dpMin[i - 1] * nums[i], nums[i]));
            dpMin[i] = Math.min(dpMax[i - 1] * nums[i], Math.min(dpMin[i - 1] * nums[i], nums[i]));
            res = Math.max(dpMax[i], res);
        }

        return res;
    }
}
//leetcode submit region end(Prohibit modification and deletion)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章