给你一个整数数组 nums
,请你找出数组中乘积最大的连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。
示例 1:
输入: [2,3,-2,4]
输出: 6
解释: 子数组 [2,3] 有最大乘积 6。
示例 2:
输入: [-2,0,-1]
输出: 0
解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。
题目理解: 求数组中两个连续下标的数字最大值。
解题思路:前后遍历两次求最大乘积即可
class Solution {
public int maxProduct(int[] nums) {
// 使用1作为基础数字与数组中的元素相乘
int n = 1;
int max = nums[0];
for(int num : nums){
n = n * num;
if(max < n){
max = n;
}
// 0乘以任何数都等于0 所以重置n的值
if(n == 0){
n = 1;
}
}
n = 1;
for(int i = nums.length - 1;i >= 0;i--){
n = n * nums[i];
if(max < n){
max = n;
}
if(n == 0){
n = 1;
}
}
return max;
}
}
执行用时:0 ms
内存消耗:39.7 MB