152. Maximum Product Subarray
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.
Subscribe to see which companies asked this question
Related issue: 53. Maximum Subarray
public class Solution {
public int maxProduct(int[] nums) {
if(nums == null || nums.length == 0)
return 0;
int max = nums[0];
int min = nums[0];
int product = nums[0];
for(int i = 1; i< nums.length; i++){
int t1 = max * nums[i];
int t2 = min * nums[i];
max = Math.max(Math.max(t1, t2), nums[i]);
min= Math.min(Math.min(t1, t2), nums[i]);
product = Math.max(product, max);
}
return product;
}
}