Close
Topic list
Maximum Product Subarray
MEDIUM
25 mins
Dynamic Programming
Arrays
Topics (Covered in this problem)
Problem solved
Skill meter
Dynamic Programming
-
-
Arrays
-
-
Other topics
Problem solved
Skill meter
Strings
-
-
Matrices (2D Arrays)
-
-
-
-
Sorting
-
-
Binary Search
-
-
Stacks & Queues
-
-
Trees
-
-
Graph
-
-
Greedy
-
-
Tries
-
-
SQL
-
-
Binary Search Trees
-
-
Heap
-
-
Bit Manipulation
-
-
Solve problems & track your progress
Checkout your overall progress in every topic here
Become
Sensei
in DSA topics
Open the topic and solve more problems associated with it to improve your skills
Check out the skill meter for every topic
See how many problems you are left with to solve for cracking any stage. Score more than zero to get your progress counted.

# Maximum Product Subarray

Contributed by
Pankaj Sharma
Medium
0/80
Avg time to solve 25 mins
Success Rate 75 %
Share

## Problem Statement

#### You are given an array “arr'' of integers. Your task is to find the contiguous subarray within the array which has the largest product of its elements. You have to report this maximum product.

``````An array c is a subarray of array d if c can be obtained from d by deletion of several elements from the beginning and several elements from the end.

For e.g.- The non-empty subarrays of an array [1,2,3] will be- [1],[2],[3],[1,2],[2,3],[1,2,3].
``````
##### For Example:
``````If arr = {-3,4,5}.
All the possible non-empty contiguous subarrays of “arr” are {-3}, {4}, {5}, {-3,4}, {4,5} and {-3,4,5}.
The product of these subarrays are -3, 4, 5, -12, 20 and -60 respectively.
The maximum product is 20. Hence, the answer is 20.
``````
``````Can you solve this in linear time and constant space complexity?
``````
Detailed explanation ( Input/output format, Notes, Constraints, Images )
##### Sample Input 1:
``````2
4
3 5 -2 -4
5
2 4 3 5 6
``````
##### Sample Output 1:
``````120
720
``````
##### Explanation for sample 1:
``````For the first test case, all the possible non-empty contiguous subarrays of “arr” are {3}, {5}, {-2}, {-4}, {3,5}, {5,-2}, {-2,-4}, {3,5,-2}, {5,-2,-4} and {3,5,-2,-4}.
The product of these subarrays are 3, 5, -2, -4, 15, -10, 8, -30, 40 and 120 respectively.
So, the maximum product is 120.
For the second test case, since all the elements in the array “arr” are positive, we get the maximum product subarray by multiplying all the elements in the array. So, the maximum product is 720.
``````
##### Sample Input 2:
``````2
4
6 0 2 -4
3
-1 -3 -4
``````
##### Sample Output 2:
``````6
12
``````
Auto
Console