Taro Logo

Maximum Product Subarray

#130 Most AskedMedium
0 views
Topics:
ArraysDynamic Programming

Given an integer array nums, find a subarray that has the largest product, and return the product.

The test cases are generated so that the answer will fit in a 32-bit integer.

Example 1:

Input: nums = [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.

Example 2:

Input: nums = [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.

Constraints:

  • 1 <= nums.length <= 2 * 104
  • -10 <= nums[i] <= 10
  • The product of any subarray of nums is guaranteed to fit in a 32-bit integer.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the range of values for the elements inside the `nums` array, and can we expect extremely large numbers that might cause integer overflow?
  2. How should we handle an array with a single element or an empty input array if that is possible?
  3. Are we required to return just the maximum product value itself, or do we need to return the actual subarray (or its start and end indices)?
  4. If the array contains all negative numbers or a mix of negatives and zeros, does a single element or a zero count as a valid contiguous subarray?
  5. Can multiple subarrays share the same maximum product, and if so, does it matter which one is considered if we were to return the subarray itself?

Brute Force Solution

Approach

Imagine you have a row of numbers and you want to find a continuous group of them that multiplies together to make the biggest possible result. The brute force approach involves looking at every single possible continuous group, multiplying them out, and seeing which one wins.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very first number by itself as a group.
  2. Then consider the first number combined with the second number, and then the first number combined with the second and third numbers, and so on until you reach the end of the line.
  3. Next, move to the second number and repeat the process by building every possible group starting from that second number.
  4. Continue this exact same process for every single starting position in the entire line of numbers.
  5. Every time you form a group of numbers, multiply them all together to calculate their total product.
  6. Keep a mental note of the largest product you have calculated so far, updating it whenever you find a group that multiplies to an even bigger number.
  7. Once you have checked every possible continuous group from every possible starting point, the largest product you remembered is your final answer.

Code Implementation

def max_product_subarray(input_numbers):
    # Handle edge case where the input list is completely empty
    if not input_numbers:
        return 0

    highest_product_found = input_numbers[0]

    # Iterate through every possible starting position in the array
    for start_index in range(len(input_numbers)):
        current_group_product = 1

        # Extend the continuous group one element at a time and multiply
        for end_index in range(start_index, len(input_numbers)):
            current_group_product *= input_numbers[end_index]

            # Update our tracked maximum if the current group product is larger
            if current_group_product > highest_product_found:
                highest_product_found = current_group_product

    return highest_product_found

Big(O) Analysis

Time Complexity
O(n²) – To analyze the time complexity of this brute force approach, we look at the nested loops required to examine every possible continuous group. The outer loop selects each of the n numbers in the array as the starting position for a group. For each starting position, the inner loop extends the group one element at a time until the end of the array is reached, performing multiplications along the way. This means for the first element we check n groups, for the second n-1 groups, and so on down to 1 group for the final element. Summing these operations yields approximately n * (n + 1) / 2 total steps, which simplifies to a Big O time complexity of O(n²).
Space Complexity
O(1) – The brute force approach described relies entirely on a few primitive tracking variables, such as a mental note for the largest product and loop counters. No auxiliary data structures, temporary lists, or recursive calls are created to store intermediate groups or products. Because the memory required to maintain these scalar variables remains constant regardless of the input size, the extra space usage does not grow with N.

Optimal Solution

Approach

To find the group of numbers next to each other that multiplies to the largest possible result, we cannot just rely on keeping track of the biggest numbers seen so far. Because multiplying two negative numbers creates a positive number, we must also track the smallest negative results as we move along, just in case they suddenly flip into massive positives.

Here's how the algorithm would work step-by-step:

  1. Begin at the very first number in the sequence and set both your current highest running product and your current lowest running product to that exact number.
  2. Look at the next number coming up in the sequence.
  3. Multiply that new number by your previous highest result, your previous lowest result, and also consider the new number all by itself to see what happens.
  4. Compare those outcomes to figure out which combination gives you the absolute highest result and the absolute lowest result right now.
  5. Update your tracking records with those new highest and lowest results.
  6. Keep a separate note of the overall maximum product you have ever seen since the start of the journey.
  7. Repeat this process for every upcoming number in the sequence until you reach the end, ensuring you always know the absolute best product achieved.

Code Implementation

def max_product(array_of_numbers):
    current_max_product = array_of_numbers[0]
    current_min_product = array_of_numbers[0]
    overall_max_product = array_of_numbers[0]

    # Negatives can flip to positives, so tracking both extremes is required.
    for next_number in array_of_numbers[1:]:
        
        candidate_products = (
            next_number,
            next_number * current_max_product,
            next_number * current_min_product
        )

        current_max_product = max(candidate_products)
        current_min_product = min(candidate_products)

        # The global maximum must be updated at each step to capture the best result.
        overall_max_product = max(overall_max_product, current_max_product)

    return overall_max_product

Big(O) Analysis

Time Complexity
O(n) – To find the maximum product subarray, we iterate through the input sequence of size n exactly once from left to right. During each iteration at step seven, we perform a constant number of arithmetic operations and comparisons to update our running maximums, minimums, and overall best product. Because we visit each element in the array just once, the total number of operations scales linearly with the input size. This linear progression directly approximates n operations, which simplifies in Big O notation to O(n).
Space Complexity
O(1) – To solve this problem, the algorithm only allocates a few primitive scalar variables to track the current highest product, the current lowest product, and the overall maximum product. Because these tracking variables do not scale with the input size N, the extra memory usage remains constant regardless of how many numbers are in the sequence. There are no auxiliary arrays, hash maps, or recursive call stacks utilized during the process. Therefore, the overall auxiliary space complexity simplifies to O(1).

Edge Cases

Array of size one
How to Handle:
Return the single element immediately since a single-element subarray is contiguous and non-empty.
Array containing a single zero
How to Handle:
Return zero because the only possible non-empty contiguous subarray product is zero.
Array with alternating negative numbers
How to Handle:
Track both the maximum and minimum product at each step so that a negative minimum can flip into a large positive product upon encountering the next negative number.
Array with zeros interspersed among positive and negative numbers
How to Handle:
Reset the running maximum and minimum products to one when encountering a zero, effectively starting a new subarray search.
All elements are negative numbers with an odd length
How to Handle:
Track minimum products to ensure the algorithm correctly identifies the maximum possible product formed by all negative numbers except the smallest magnitude one.
Integer overflow from extremely large positive or negative products
How to Handle:
Use 64-bit integers or guard against overflow depending on the programming language constraints to prevent wrapping around incorrect values.
Maximum-sized inputs up to the problem constraints limit
How to Handle:
Use an O(n) time and O(1) space dynamic programming approach to ensure the solution executes within time limits and memory constraints.
0/257 completed