Maximum Product Subarray — LeetCode 152 Python Solution
- Problem
- #152
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(n·m) or optimized auxiliary |
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
On study lists
This problem is on Blind 75 and NeetCode 150.
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.