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: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1] Output: 0 Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
使用动态规划,但是要注意,避免正负数出错,应该保存当前最大值和当前最小值 如[-2,3,-4]
1 public int maxProduct(int[] nums) {//dp mytip 2 if(null==nums||0==nums.length){ 3 return 0; 4 } 5 int max = nums[0]; 6 int min = nums[0]; 7 int re = nums[0]; 8 for(int i=1;i<nums.length;i++){//max=Max(max*nums[i],min*nums[i],nums[i]) 9 //min=Min(max*nums[i],min*nums[i],nums[i]) 10 int p = max*nums[i]; 11 int q = min*nums[i]; 12 if(p>q){ 13 max = p; 14 min = q; 15 } 16 else{ 17 min =p; 18 max = q; 19 } 20 max = max>nums[i]?max:nums[i]; 21 min = min>nums[i]?nums[i]:min; 22 re = re>max?re:max; 23 } 24 return re; 25 }