152. Maximum Product Subarray
Given an integer array nums
, find a
that has the largest product, and return the product.
The test cases are generated so that the answer will fit in a 32-bit integer.
Example 1:
Input: nums = [2,3,-2,4] Output: 6 Explanation: [2,3] has the largest product 6.
Example 2:
Input: nums = [-2,0,-1] Output: 0 Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
class Solution {
public int maxProduct(int[] arr) {
int n = arr.length;
int curMin = arr[0];
int curMax = arr[0];
int maxPro = arr[0];
for(int i = 1;i<n;i++){
int temp = Max(arr[i],arr[i] * curMin,arr[i] * curMax);
curMin = Min(arr[i],arr[i] * curMin,arr[i] * curMax);
curMax = temp;
maxPro = Math.max(maxPro,curMax);
}
return maxPro;
}
private int Max(int a,int b,int c){
return Math.max(a,Math.max(b,c));
}
private int Min(int a,int b,int c){
return Math.min(a,Math.min(b,c));
}
}
Comments
Post a Comment