MediumNo. 0152
Maximum Product Subarray — LeetCode 152 Python Solution
- Pattern
- Dynamic Programming
- Topics
- Array, Dynamic Programming
- On study lists
- Blind 75 and NeetCode 150
- 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
- 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
| No. | Problem | Difficulty |
|---|---|---|
| 0045 | Jump Game II | Medium |
| 0053 | Maximum Subarray | Medium |
| 0055 | Jump Game | Medium |
| 0063 | Unique Paths II | Medium |
| 0064 | Minimum Path Sum | Medium |
| 0085 | Maximal Rectangle | Hard |
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.