Tutorialspoint
Problem
Solution
Submissions

Maximum Product Subarray

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 15

Write a C program to find the maximum product of a contiguous subarray within a one-dimensional array of integers. The subarray must contain at least one element. Handle both positive and negative numbers, including the case where the array contains zeros.

Example 1
  • Input: arr = [2, 3, -2, 4]
  • Output: 6
  • Explanation: The subarray [2, 3] has the maximum product.
Example 2
  • Input: arr = [-2, 0, -1]
  • Output: 0
  • Explanation: The subarray [0] has the maximum product.
Constraints
  • 1 ≤ arr.length ≤ 2 * 10^4
  • -10 ≤ arr[i] ≤ 10
  • The product of any prefix or suffix of arr is guaranteed to fit in a 32-bit integer
  • Time Complexity: O(n)
  • Space Complexity: O(1)
ArraysPwCSwiggy
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Keep track of both maximum and minimum products ending at each position
  • At each element, the new maximum product can be the current element, current element multiplied by previous maximum, or current element multiplied by previous minimum
  • Similarly for minimum product, since multiplying two negatives gives positive
  • Update the global maximum at each step

Steps to solve by this approach:

 Step 1: Initialize maxProd, minProd, and result with the first element
 Step 2: Iterate through the array starting from the second element
 Step 3: If current element is negative, swap maxProd and minProd
 Step 4: Update maxProd as maximum of current element or current element multiplied by previous maxProd
 Step 5: Update minProd as minimum of current element or current element multiplied by previous minProd
 Step 6: Update the global result if current maxProd is greater
 Step 7: Return the final result

Submitted Code :