Maximum Product Subarray

Maximum Product Subarray Problem

Given an integer array nums, find the subarray with the maximum product and return its value.

A sub array is a continuous, non-empty portion of the array.

You can assume the result will fit within a 32-bit integer.

maximum product subarray problem

Constraints:

  • 1 <= nums.length <= 1000
  • -10 <= nums[i] <= 10

Maximum Product Subarray Solution

Approaches for solving Maximum Product Subarray problem

There are mainly 4 approach to solve this problem 

  1. Brute Force Method
  2. Sliding Window Method
  3. Kadane’s Algorithm Method
  4. Prefix & Suffix

1. Brute Force Method:

Check all possible subarrays in the array, calculate their products, and track the maximum product found. This method is simple but inefficient for large arrays as it checks every combination.

  • Time complexity: O(n^2)
  • Space complexity: O(1)

Code

2. Sliding Window  Method

Use a sliding window to iterate through the array while keeping track of the current product, updating it as you move the window. This approach is faster but still needs care with negative numbers.

  • Time complexity: O(n)
  • Space complexity: O(n)

Code

3. Kadane’s Algorithm

Modify Kadane’s algorithm to handle products by keeping track of both the maximum and minimum products at each index. This efficiently handles both positive and negative numbers.

  • Time complexity: O(n)
  • Space complexity: O(1)

Code

4. Prefix and Suffix Method

Precompute prefix and suffix products for the array, then find the maximum product by checking combinations of these values. This method reduces time complexity but uses extra space.

  • Time complexity: O(n)
  • Space complexity: O(1)

Code

More Articles