Back to blog
Dec 02, 2024
2 min read

LeetCode 152: Maximum Product Subarray

Leetcode 152: Maximum Product Subarray solution in Python

Problem Description

LeetCode Problem 152

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.

Difficulty: Medium

Tags: array, dynamic programming

Rating: 96.16%

Solution

Here’s my Python solution to this problem:

class Solution:
    def maxProduct(self, nums: List[int]) -> int:
        if not nums: return 0

        curr_max = curr_min = result = nums[0]
    
        for num in nums[1:]:
            temp_max = curr_max
            
            # For each number, we need to compare:
            # 1. The number itself
            # 2. Number * current maximum (could be good if both are positive or both negative)
            # 3. Number * current minimum (could be good if both are negative)
            curr_max = max(num, temp_max * num, curr_min * num)
            curr_min = min(num, temp_max * num, curr_min * num)
            
            result = max(result, curr_max)
        
        return result

Complexity Analysis

The solution has the following complexity characteristics:

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

Note: This is an automated analysis and may not capture all edge cases or specific algorithmic optimizations.