给你一个整数数组 nums ,请你找出数组中乘积最大的连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。
示例 1:
输入: [2,3,-2,4]
输出: 6
解释: 子数组 [2,3] 有最大乘积 6。
示例 2:
输入: [-2,0,-1]
输出: 0
解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。
1.暴力法。
class Solution {
public int maxProduct(int[] nums) {
int maxNum = Integer.MIN_VALUE;
int currentNum = 1;
for(int i = 0;i < nums.length;i++){//每个元素为起点
for(int j = i;j < nums.length;j++){//遍历从起来开始往后的每个元素,计算当前乘积
currentNum *= nums[j];
if(currentNum > maxNum){
maxNum = currentNum;
}
}
currentNum = 1;//当前起点遍历完后,重置currentNum
}
return maxNum;
}
}
2.动态规划。因为有正负数的情况,如果当前数是正数,那么前面的子数组的正数尽可能大。即最大值;如果当前数是负数,那么前面的子数组的负数积尽可能大&