题目描述
思路分析
换种思路去想,如果数组全是正数,那么最大值就是数组中所有值得乘积。如果数组中有负数,那么只要保证子数组中含有偶数个负数就可以实现最大值。注意
:还要考虑子数组中可能含有0,如果在遍历时遇到0,就将max值置为1,进行下一次的最大值求解。
代码实现
public int maxProduct(int[] nums) {
if (nums.length == 0) {
return 0;
}
int max = 1;
int res = nums[0];
//包含了所有数相乘的情况
//奇数个负数的情况一
for (int i = 0; i < nums.length; i++) {
max *= nums[i];
res = Math.max(res, max);
if (nums[i] == 0) {
max = 1;
}
}
max = 1;
//奇数个负数的情况二
for (int i = nums.length - 1; i >= 0; i--) {
max *= nums[i];
res = Math.max(res, max);
if (nums[i] == 0) {
max = 1;
}
}
return res;
}