Given an integer array, find the subarray that has the maximum product of its elements. The solution should return the maximum product of elements among all possible subarrays.

For example,

Input:  { -6, 4, -5, 8, -10, 0, 8 }
Output: 1600
Explanation: The maximum product subarray is {4, -5, 8, -10} having product 1600
 
 
Input:  { 40, 0, -20, -10 }
Output: 200
Explanation: The maximum product subarray is {-20, -10} having product 200

Practice this problem

The problem differs from the problem of finding the maximum product subsequence. Unlike subsequences, subarrays are required to occupy consecutive positions within the original array.

 
A naive solution would be to consider every subarray and find the product of their elements. Finally, return the maximum product found among all subarrays. The implementation can be seen here. The time complexity of this solution is O(n2), where n is the size of the input.

 
A better solution will be to maintain two variables to store the maximum and minimum product ending in the current position. Then traverse the array once, and for every index i in the array, update the maximum and minimum product ending at A[i]. Update the result if the maximum product ending at any index is more than the maximum product found so far.

Following is the C, Java, and Python implementation based on the above idea:

C


Download  Run Code

Output:

The maximum product of a subarray is 1600

Java


Download  Run Code

Output:

The maximum product of a subarray is 1600

Python


Download  Run Code

Output:

The maximum product of a subarray is 1600

The time complexity of the above solution is O(n) and doesn’t require any extra space.