
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find maximum product of contiguous subarray in Python
Suppose we have an array called nums, we have to find the product of elements of a contiguous subarray within an array (containing at least one number) which has the largest product. So if the array is [1,9,2,0,2,5], the output will be 18, as contiguous subarray [1,9,2] has max product.
To solve this, we will follow these steps −
- max_list := list of size nums, and fill with 0
- min_list := list of size nums, and fill with 0
- min_list := list of size nums, and fill with 0
- for i in range 1 to length of nums
- max_list[i] = max of max_list[i - 1]*nums[i], min_list[i - 1]*nums[i] and nums[i]
- min_list[i] = minof min_list[i - 1]*nums[i], nums[i], max_list[i - 1]*nums[i]
- return the max of max_list
Let us see the following implementation to get better understanding −
Example
class Solution(object): def maxProduct(self, nums): max_list = [0] * len(nums) min_list = [0] * len(nums) max_list[0] = nums[0] min_list[0] = nums[0] for i in range(1,len(nums)): max_list[i] = max(max(max_list[i-1]*nums[i],min_list[i-1]*nums[i]),nums[i]) min_list[i] = min(min(min_list[i-1]*nums[i],nums[i]),max_list[i-1]*nums[i]) return max(max_list) ob1 = Solution() print(ob1.maxProduct([1,9,2,0,2,5]))
Input
[1,9,2,0,2,5]
Output
18
- Related Articles
- Program to find maximum subarray min-product in Python
- C++ program to find maximum of each k sized contiguous subarray
- Program to find maximum length of subarray with positive product in Python
- Maximum contiguous sum of subarray in JavaScript
- Maximum Product Subarray in Python
- Program to find sum of contiguous sublist with maximum sum in Python
- Program to find maximum absolute sum of any subarray in Python
- Program to find maximum score of a good subarray in Python
- Program to find maximum ascending subarray sum using Python
- Largest product of contiguous digits in Python
- Maximum Product Subarray | Added negative product case in C++
- Program to find the maximum sum of the subarray modulo by m in Python
- C/C++ Program for Largest Sum Contiguous Subarray?
- Largest Sum Contiguous Subarray
- Program to find out the sum of the maximum subarray after a operation in Python

Advertisements