MediumNo. 0152

Maximum Product Subarray — LeetCode 152 Python Solution

Topics
Array, Dynamic Programming
On study lists
Blind 75 and NeetCode 150
Reading time
2 min

The problem

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

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

Python solution

PythonSolution
class Solution:
    def maxProduct(self, nums: List[int]) -> int:
        ans = f = g = nums[0]
        for x in nums[1:]:
            ff, gg = f, g
            f = max(x, ff * x, gg * x)
            g = min(x, ff * x, gg * x)
            ans = max(ans, f)
        return ans

Complexity

Time
O(n·m) (typical)
Space · auxiliary
O(n·m)or optimized

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 152. Maximum Product Subarray is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0045Jump Game IIMedium
0053Maximum SubarrayMedium
0055Jump GameMedium
0063Unique Paths IIMedium
0064Minimum Path SumMedium
0085Maximal RectangleHard

Frequently asked questions

How hard is LeetCode 152. Maximum Product Subarray?

LeetCode 152. Maximum Product Subarray is rated Medium on LeetCode.

What topics does LeetCode 152. Maximum Product Subarray cover?

LeetCode 152. Maximum Product Subarray is tagged Array and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.