Leetcode - Maximum Product Subarray Solution
1 min read

# 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

# Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

That's okay. But without advertising-income, we can't keep making this site awesome.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add thepoorcoder.com to your ad blocking whitelist or disable your adblocking software.

×