Find the contiguous subarray within an array (containing at least one number) which have the largest product.
For example, given the array [2,3,-2,4]
,
The contiguous Subarray has the [2,3]
largest product = 6
.
Idea: DP. Here we don't actually need O (n) space, just record the maximum value that the variable will traverse to.
Where, because the product of the number, it is possible that the original two are negative values multiplied will become the largest product.
Therefore, we need to maintain two variables, maxpre and Minpre.
Maxpre the last digit is the maximum product of the interval of the previous position in the current location.
Minpre the last digit is the smallest product of the interval before the current position.
Then, taking into account the current position, there are:
Maxsofar = Max (max (Maxpre * nums[i], Minpre * nums[i]), nums[i]);
Minsofar = min (min (minpre * nums[i], Maxpre * nums[i]), nums[i]);
The maxresfound is then used to record the maximum value of the Maxsofar during the iteration, which is the result.
1 classSolution {2 Public:3 intMaxproduct (vector<int>&nums) {4 intn =nums.size ();5 if(n = =0)return 0;6 intMaxsofar, Minsofar, Maxresfound, Maxpre, Minpre;7Maxpre = Minpre = Maxsofar = Minsofar = Maxresfound = nums[0];8 for(inti =1; I < n; i++)9 {TenMaxsofar = Max (max (Maxpre * nums[i), Minpre *nums[i]), nums[i]); OneMinsofar = min (min (minpre * nums[i), Maxpre *nums[i]), nums[i]); AMaxresfound =Max (Maxresfound, Maxsofar); -Maxpre =Maxsofar; -Minpre =Minsofar; the } - returnMaxresfound; - } -};
Maximum Product Subarray-leetcode