题目所属分类
原题链接
给你一个整数数组 nums ,请你找出数组中乘积最大的非空连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。
测试用例的答案是一个 32-位 整数。
子数组 是数组的连续子序列。
代码案例:输入: nums = [2,3,-2,4]
输出: 6
解释: 子数组 [2,3] 有最大乘积 6。
题解
class Solution {
public int maxProduct(int[] nums) {
int res = nums[0] ;
int f = nums[0] , g = nums[0] ;
for(int i = 1 ; i < nums.length ;i++){
int a = nums[i] , fa = f*a , ga = g*a ;
f = Math.max(a , Math.max(fa , ga));
g = Math.min(a , Math.min(fa,ga));
res = Math.max(res , f );
}
return res ;
}
}