標籤:osi 遍曆 one 變數 自己的 span 全域最優 exp 根據
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]Output: 6Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]Output: 0Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
暴力解法應該會逾時吧,直接考慮用動態規劃。用dp[i]來儲存以nums[i]為結尾的數組的子序列的最大乘積。有一個問題是根據dp[i-1]求dp[i]時,需要判斷nums[i]對全域的影響。因為符號對乘法的影響會使結果不能作為局部最優解,但仍然保留著成為全域最優解的可能。所以同時需要用兩個變數儲存當前最大的正數乘積,以及最小的負數乘積。當遍曆到nums[i]時需要同時更新dp[i],maxPositive以及minNegative。具體的遞推是,更新maxPositive,minNegative,之後dp[i]取dp[i-1]和maxPositive中的最大值。更新最大正乘積以及最小負乘積時要記得考慮只有元素自己的情況,並且要分別獨立更新。當然本題不需要儲存dp[0] ~ dp[i-1],因為dp[i]嚴格的只和dp[i-1]有關,所以只需要一個dp來儲存上一個位置即可,空間可以最佳化成常數。
Java
class Solution { public int maxProduct(int[] nums) { if (nums == null || nums.length == 0) return 0; int maxP = nums[0], minN = nums[0], dp = nums[0]; for (int i = 1; i < nums.length; i++) { int locMax = nums[i] * maxP, locMin = nums[i] * minN; maxP = Math.max(nums[i], Math.max(locMax, locMin)); minN = Math.min(nums[i], Math.min(locMax, locMin)); dp = Math.max(dp, maxP); } return dp; }}
(Java) LeetCode 152. Maximum Product Subarray —— 乘積最大子序列