Given an integer array nums
, find the contiguous subarray within a array (containing at least one number) which have 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] was not a subarray.
The brute force solution should be timed out, with a direct consideration of dynamic programming. Use Dp[i] to store the maximum product of the subsequence of an array ending with nums[i]. One problem is that when dp[i-1] dp[i], it is necessary to determine the impact of nums[i] on the global. Because the influence of the symbol on multiplication makes the result not be the local optimal solution, it still retains the possibility of becoming the global optimal solution. So at the same time, two variables are required to store the current maximum positive product and the smallest negative product. You need to update both dp[i],maxpositive and minnegative when traversing to nums[i]. The specific recursion is, update maxpositive,minnegative, then Dp[i] take dp[i-1] and the maximum value in maxpositive. When updating the maximum positive product and the minimum negative product, remember to consider only the element's own situation, and to independently update it separately. Of course, the subject does not need to store dp[0] ~ dp[i-1], because dp[i] strict only and dp[i-1], so only a DP to store the previous location, space can be optimized to a constant.
Java
classSolution { Public intMaxproduct (int[] nums) { if(Nums = =NULL|| Nums.length = = 0)return0; intMAXP = Nums[0], Minn = nums[0], DP = nums[0]; for(inti = 1; i < nums.length; i++) { intLocmax = 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); } returnDP; }}
(Java) Leetcode 152. Maximum Product subarray--Product maximum sub-sequence