152. Maximum Product Subarray & 1567. Maximum Length of Subarray With Positive Product
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.class Solution {
public int maxProduct(int[] nums) {
if (nums == null || nums.length <= 0) return 0;
// 这里全部初始化为第一个数
int max = nums[0], min = nums[0], res = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] > 0) {
// 注意这里虽然此数是正数,还是要这样写。因为max/min有可能是0.
max = Math.max(max * nums[i], nums[i]);
min = Math.min(min * nums[i], nums[i]);
} else {
int temp = max;
max = Math.max(min * nums[i], nums[i]);
min = Math.min(temp * nums[i], nums[i]);
}
res = Math.max(res, max);
}
return res;
}
}Last updated