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