![]() |
VOOZH | about |
Given an array arr[] consisting of positive, negative, and zero values, find the maximum product that can be obtained from any contiguous subarray of arr[].
Examples:
Input: arr[] = [-2, 6, -3, -10, 0, 2]
Output: 180
Explanation: The subarray with maximum product is [6, -3, -10] with product = 6 * (-3) * (-10) = 180.Input: arr[] = [-1, -3, -10, 0, 6]
Output: 30
Explanation: The subarray with maximum product is [-3, -10] with product = (-3) * (-10) = 30.Input: arr[] = [2, 3, 4]
Output: 24
Explanation: For an array with all positive elements, the result is product of all elements.
Table of Content
The idea is to traverse over every contiguous subarray, find the product of each of these subarrays and return the maximum product among all the subarrays.
180
The main idea is to traverse the array while keeping track of both the maximum and minimum product ending at each index. A zero resets the product since any subarray containing it has product zero, while a negative number can turn a minimum product into a maximum one. By maintaining both values, we can correctly compute the maximum product subarray in a single pass.
Working:
180
We keep a running product while traversing the array and reset it to
1whenever we encounter0. The issue occurs when there is an odd number of negative elements, making the product negative. Since the subarray must be contiguous, we can only exclude the first or last negative element. Traversing from both the start and the end allows us to handle both cases and find the maximum product subarray.
Illustration:
180