题目
给你一个整数数组 nums ,请你找出数组中乘积最大的连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。
示例
输入: [2,3,-2,4]
输出: 6
解释: 子数组 [2,3] 有最大乘积 6。
输入: [-2,0,-1]
输出: 0
解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。
代码由于这道题目存在负数,所以我们同样需要考虑每次比较最小的情况
class Solution {
public int maxProduct(int[] nums) {
if(nums.length==1){return nums[0];}
int max=nums[0];
//nums1[i]存储以i结尾的乘积最大值
int[]nums1=new int[nums.length];
//nums2[i]存储以i结尾的乘积的最小值
int[]nums2=new int[nums.length];
nums1[0]=nums[0];
nums2[0]=nums[0];
for(int i=1;i<nums.length;i++){
if(nums[i]<0){
nums1[i]=Math.min(nums2[i-1]*nums[i],nums[i]);
nums2[i]=Math.max(nums1[i-1]*nums[i],nums[i]);
}else{
nums1[i]=Math.min(nums1[i-1]*nums[i],nums[i]);
nums2[i]=Math.max(nums2[i-1]*nums[i],nums[i]);
}
max=Math.max(max,nums2[i]);
}
return max;
}
}