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.
public class MaximumProductSubArray {
public static void main(String[] args) {
int[] arr = {-2,1,-4};
int result = arr[0];
int max = arr[0];
int min = arr[0];
for(int i=1;i<arr.length;i++){
int tempMax = Math.max(arr[i], Math.max(max*arr[i],min*arr[i]));
min = Math.min(arr[i], Math.min(max*arr[i],min*arr[i]));
max = tempMax;
result = Math.max(result,max);
}
System.out.println(result);
}
}
Result:8
No comments:
Post a Comment