☄️Intuition The idea is to find the maximum product of a subarray in the given array of integers. This problem can be tricky because negative numbers can flip the product, and we may have to consider both the prefix (left to right) and suffix (right to left) arrays to make sure we don't miss any potential maximum product.
🧠Approach - Two Traversals: Instead of maintaining only one running product, we maintain two:
One for the prefix product, going from left to right.
Another for the suffix product, going from right to left.
Reset on Zero: Since a product becomes 0 when any element is zero, we reset the product to 1 when encountering a zero.
Keep Track of Max Product: During each traversal, we keep updating the maximum product encountered so far.
🛠️ How it works: We keep two products:
Prefix: Starts multiplying numbers from the left.
Suffix: Starts multiplying numbers from the right.
At each step, we check the product of both the prefix and suffix and update the maximum product found.
If we encounter a zero, the product will be reset to 1, since multiplying by zero ruins the subarray product.
⏳Complexity O(n): We are making only a single pass through the array, which means the time complexity is linear.
O(1): We only use a few extra variables (prefix, suffix, max), so the space complexity is constant.
public class Solution {
public static int subarrayWithMaxProduct(int []arr){
// Write your code here.
int n=arr.length;
int prefix=1;
int suffix=1;
int max=Integer.MIN_VALUE;
for(int i=0;i<n;i++)
{
if(prefix==0)
prefix=1;
else if(suffix==0)
suffix=1;
suffix=suffix*arr[i];
prefix=prefix*arr[n-i-1];
max=Math.max(max,Math.max(prefix,suffix));
}
return max;
}
}