![]() |
VOOZH | about |
Given an array that contains both positive and negative integers, find the product of the maximum product subarray. Expected Time complexity is O(n) and only O(1) extra space can be used.
Examples :
Input: arr[] = {6, -3, -10, 0, 2}
Output: 180 // The subarray is {6, -3, -10}
Input: arr[] = {-1, -3, -10, 0, 60}
Output: 60 // The subarray is {60}
Input: arr[] = {-1, -2, -3, 4}
Output: 24 // The subarray is {-2, -3, 4}
Input: arr[] = {-10}
Output: 0 // An empty array is also subarray
// and product of empty subarray is
// considered as 0.
We have discussed a solution of this problem here.
In this post an interesting solution is discussed. The idea is based on the fact that overall maximum product is maximum of following two:
For example, consider the above third sample input {-1, -2, -3, 4}. If we traverse the array only in forward direction (considering -1 as part of output), maximum product will be 2. If we traverse the array in backward direction (considering 4 as part of output), maximum product will be 24 i.e; { -2, -3, 4}.
One important thing is to handle 0's. We need to compute fresh forward (or backward) sum whenever we see 0.
Below is the implementation of above idea :
24
Time Complexity : O(n)
Auxiliary Space : O(1)
Note that the above solution requires two traversals of an array while the previous solution requires only one traversal.