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.
Constraints:
1 <= nums.length <= 2 * 104-10 <= nums[i] <= 10- The product of any subarray of
numsis guaranteed to fit in a 32-bit integer.
Approach
- Use prefix and suffix product, the way it moves from both side it seems to ensure to cover all subarrays
- If we encounter a zero then set prefix and suffix as 1
class Solution {
public int maxProduct(int[] nums) {
int p = 1, s = 1;
int m = Integer.MIN_VALUE;
for (int i = 0; i < nums.length; i++) {
if (p == 0) p = 1;
if (s == 0) s = 1;
p *= nums[i];
s *= nums[nums.length - i - 1];
m = Math.max(m, Math.max(p,s));
}
return m;
}
}