Tutorialspoint
Problem
Solution
Submissions

Maximum Product Subarray

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

Write a C# program to implement the MaxProduct(int[] nums) function, which finds the contiguous subarray within an array of integers that has the largest product. The function should return the product of that subarray.

Example 1
  • Input: nums = [2, 3, -2, 4]
  • Output: 6
  • Explanation:
    • Step 1: Consider all possible subarrays of the input array.
    • Step 2: Calculate the product of each subarray.
    • Step 3: The subarray [2, 3] has the largest product = 6.
    • Step 4: Return the maximum product, which is 6.
Example 2
  • Input: nums = [-2, 0, -1]
  • Output: 0
  • Explanation:
    • Step 1: Consider all possible subarrays of the input array.
    • Step 2: Calculate the product of each subarray.
    • Step 3: The subarray [0] has the largest product = 0.
    • Step 4: Return the maximum product, which is 0.
Constraints
  • 1 ≤ nums.length ≤ 2 * 10^4
  • -10 ≤ nums[i] ≤ 10
  • The array may contain both positive and negative integers
  • Time Complexity: O(n) where n is the length of the input array
  • Space Complexity: O(1) for constant extra space
ArraysNumberEYeBay
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
  • The minimum product is useful when the next element is negative (negative * negative = positive)
  • When encountering zero, reset both maximum and minimum products
  • Update the overall maximum product after processing each element
  • Handle edge cases like single-element arrays

Steps to solve by this approach:

 Step 1: Initialize variables to track current maximum product, current minimum product, and overall maximum product.
 Step 2: Set all initial values to the first element of the array.
 Step 3: Iterate through the array starting from the second element.
 Step 4: For each element, calculate potential new maximum and minimum products considering the current element.
 Step 5: Update maximum and minimum products based on the calculations.
 Step 6: Update the overall maximum product if the current maximum is greater.
 Step 7: Return the overall maximum product after processing the entire array.

Submitted Code :