Design Gurus Logo
Blind 75

Problem Statement

Given an integer array, find the contiguous subarray (at least one number in it) that has the maximum product. Return this maximum product.

Examples

    • Input: [2,3,-2,4]
    • Expected Output: 6
    • Justification: The subarray [2,3] has the maximum product of 6.
    • Input: [-2,0,-1]
    • Expected Output: 0
    • Justification: The subarray [0] has the maximum product of 0.
    • Input: [-2,3,2,-4]
    • Expected Output: 48
    • Justification: The subarray [-2,3,2,-4] has the maximum product of 48.

Constraints:

  • 1 <= nums.length <= 2*10<sup>4</sup>
  • -10 <= nums[i] <= 10
  • The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

Solution

  • Initialization:

    • Start by initializing two variables, maxCurrent and minCurrent, to the first element of the array. These variables will keep track of the current maximum and minimum product, respectively.
    • Also, initialize a variable maxProduct to the first element of the array. This will store the maximum product found so far.
  • Iterate through the array:

    • For each number in the array (starting from the second number), calculate the new maxCurrent by taking the maximum of the current number, the product of maxCurrent and the current number, and the product of minCurrent and the current number.
    • Similarly, calculate the new minCurrent by taking the minimum of the current number, the product of maxCurrent and the current number, and the product of minCurrent and the current number.
    • Update maxProduct by taking the maximum of maxProduct and maxCurrent.
  • Handle negative numbers:

    • Since a negative number can turn a large negative product into a large positive product, we need to keep track of both the maximum and minimum product at each step.
  • Return the result:

    • After iterating through the entire array, maxProduct will have the maximum product of any subarray.

Algorithm Walkthrough

Let's trace the third example, [-2, 3, 2, -4]. Move through the steps one at a time:

mediaLink

Step 1. Sweeping once and carrying the best product so far almost works, and fails on negatives: multiplying a large positive by a negative gives a large negative, while multiplying a large NEGATIVE by a negative gives a large positive. So the smallest product ending at each position has to be carried alongside the largest. It is not junk being tracked defensively, it is a candidate one multiplication away from winning.

1 of 6

Code

Python3
Python3

Complexity Analysis

  • Time Complexity: O(n) - We iterate through the array only once.
  • Space Complexity: O(1) - We use a constant amount of space regardless of the input size.
No code editor for this lesson
This lesson focuses on concepts and theory