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,46Explanation: [2,3] has the largest product 6.
Example 2:
Input: [ -2,0,-102, because [ -2,-1] is not a subarray.
Test instructions
To find the maximum product sub-array
Ideas:
Negative negative positive, negative minus.
/Maximum product sub-array * nums[i]
So the nums[i] end of the maximum product sub-array depends on the end of Nums[i-1]
\ Minimum product sub-array * nums[i]
Code:
1 classSolution {2 Public intMaxproduct (int[] nums) {3 int[] max =New int[nums.length];4 int[] min =New int[nums.length];5Max[0] = nums[0];6Min[0] = nums[0];7 intresult = Nums[0];8 for(inti = 1; i < nums.length; i++){9Max[i] = Math.max (Math.max (max[i-1] * nums[i], min[i-1]*nums[i]), nums[i]);TenMin[i] = Math.min (Math.min (max[i-1] * nums[i], min[i-1]*nums[i]), nums[i]); Oneresult =Math.max (result, max[i]); A } - returnresult; - } the}
[leetcode]152. Maximum Product Subarray Maximum product sub-array