Leetcode - Maximum Product Subarray Solution

Given an integer array nums, find a contiguous non-empty subarray within the array 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.

A subarray is a contiguous subsequence of the array.

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.

Solution in Python3

class Solution:
def maxProduct(self, nums: List[int]) -> int:
maxv = 1
minv = 1
best = -11
n = len(nums)
for i in range(0,n):
a = nums[i]*maxv
b = nums[i]*minv
maxv = max(a,b,nums[i])
minv = min(a,b,nums[i])
best = max(maxv, best)
maxv = maxv or 1
minv = minv or 1

return best

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe