VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-product-subarray/

⇱ Maximum Product Subarray - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum Product Subarray

Last Updated : 23 Mar, 2026

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.

[Naive Approach] Using Two Nested Loops – O(n^2) Time and O(1) Space

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.


Output
180

[Expected Approach - 1] Track of Min and Max - O(n) Time and O(1) Space

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:


Output
180

[Expected Approach - 2] By Traversing in Both Directions - O(n) Time and O(1) Space

We keep a running product while traversing the array and reset it to 1 whenever we encounter 0. 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:


Output
180
Comment