Python | Consecutive element maximum product
Last Updated :
18 May, 2023
Sometimes, we might have a problem in which we require to get the maximum product of 2 numbers from list but with a constraint of having the numbers in successions. This type of problem can occur while competitive programming. Let's discuss certain ways in which this problem can be solved.
Method #1: Using max() + zip() + list comprehension This problem can be solved using the combination of above three function in which max function can be used to get the maximum value, zip and list comprehension doing the task of extending the logic to the whole list.
Python3
# Python3 code to demonstrate
# Consecutive element maximum product
# using zip() + max() + list comprehension
# initializing string
test_string = '2312231223124565128998'
# printing original string
print("The original string : " + str(test_string))
# using zip() + max() + list comprehension
# Consecutive element maximum product
test_string = list(test_string)
res = max(int(a) * int(b) for a, b in zip(test_string, test_string[1:]))
# print result
print("The maximum consecutive product is : " + str(res))
Output : The original string : 2312231223124565128998
The maximum consecutive product is : 81
Time Complexity: O(n*n) where n is the number of elements in the dictionary. The max() + zip() + list comprehension is used to perform the task and it takes O(n*n) time.
Auxiliary Space: O(1) constant additional space is required
Method #2 : Using max() + map() + operator.mul The above problem can also be solved using yet another combination of functions. In this combination, map functions performs the task of extending the logic to whole list and mul operator is used to perform the multiplication.
Python3
# Python3 code to demonstrate
# Consecutive element maximum product
# using max() + map() + operator.mul
from operator import mul
# initializing string
test_string = '6543452345456987653234'
# printing original string
print("The original string : " + str(test_string))
# using max() + map() + operator.mul
# Consecutive element maximum product
res = max(map(mul, map(int, test_string), map(int, test_string[1:])))
# print result
print("The maximum consecutive product is : " + str(res))
Output : The original string : 6543452345456987653234
The maximum consecutive product is : 72
Time complexity: O(n), where n is the length of the input string test_string.
Auxiliary space: O(1), as the code uses constant extra space. The variables used to store the input string and the result are of constant size and do not increase with the size of the input.
Method #3: Using a sliding window
This method involves iterating through the list with a "sliding window" of size 2, and updating the maximum product as you go along.
Python3
def max_consecutive_product(lst):
# Initialize max_product to the smallest possible value
max_product = float('-inf')
# Iterate through the list with a "sliding window" of size 2
for i in range(len(lst) - 1):
# Calculate the product of the current pair
product = lst[i] * lst[i+1]
# Update max_product if necessary
max_product = max(max_product, product)
# Print the original list
print("Original list:", lst)
# Return the maximum consecutive product
return max_product
print(max_consecutive_product([1, 2, 3, 4]))
# Output:
# Original list: [1, 2, 3, 4]
# 6 (maximum product is achieved with pair (2, 3))
#This code is contributed by Edula Vinay Kumar Reddy
OutputOriginal list: [1, 2, 3, 4]
12
Time complexity: O(n)
Auxiliary Space: O(1)
NumPy approach to find the maximum product of consecutive elements in a list:
Algorithm:
- Convert the input string to a NumPy array.
- Use the NumPy roll() function to create a 2D array containing all the consecutive pairs of elements in the array.
- Use the NumPy prod() function to compute the product of each pair.
- Use the NumPy max() function to find the maximum product.
Python3
import numpy as np
# Function to find the maximum consecutive product
def max_consecutive_product(lst):
# Convert input list to NumPy array
arr = np.array(lst)
# Create 2D array of consecutive pairs
# using NumPy roll()
pairs = np.roll(arr, -1)[:-1]
pairs = np.vstack((arr[:-1], pairs)).T
# Compute product of each pair using
# NumPy prod()
products = np.prod(pairs, axis=1)
# Find maximum product using NumPy max()
max_product = np.max(products)
# Print original list and return
# the maximum product
print("Original list:", lst)
return max_product
# Driver Code
print(max_consecutive_product([1, 2, 3, 4]))
Output:
Original list: [1, 2, 3, 4]
12
Time complexity: O(n), where n is the length of the input list.
Space complexity: O(n), as the input list is converted to a NumPy array, which takes up O(n) space, and additional space is used for the pairs and products arrays, which also take up O(n) space.
METHOD 5:Using re and heapq.
APPROACH:
This program finds the maximum product of two consecutive elements in a list of integers that is given as a string.
ALGORITHM:
1.Use the re module to extract all the integers from the input string and convert them to a list.
2.Convert the list into a heap using the heapify function from the heapq module.
3.Initialize a variable max_product to negative infinity.
4.While the length of the heap is greater than 1, pop the two smallest elements from the heap using the heappop function.
5.Multiply the two elements together to get the product.
6.If the product is greater than max_product, update max_product.
7.Push the larger of the two elements back into the heap using the heappush function.
8.Once the heap has fewer than two elements, print max_product.
Python3
import re
import heapq
input_string = "Original list: [1, 2, 3, 4]"
integers = [int(num) for num in re.findall(r'\d+', input_string)]
heapq.heapify(integers)
max_product = float('-inf')
while len(integers) > 1:
a = heapq.heappop(integers)
b = heapq.heappop(integers)
product = a * b
if product > max_product:
max_product = product
heapq.heappush(integers, max(a, b))
print("Maximum product of consecutive elements:", max_product)
OutputMaximum product of consecutive elements: 12
Time complexity: O(n log n)
Auxiliary Space: O(n)
Similar Reads
Python - Maximum consecutive elements percentage change Sometimes, while working with Python lists, we can have a problem in which we need to extract the maximum change of consecutive elements. This kind of problem can have application in domains such as Data Science. Let's discuss certain ways in which this task can be performed. Input : test_list = [4,
5 min read
Python - Maximum length consecutive positive elements Sometimes, while working with Python lists, we can have a problem in which we monitor a sequence and we need to find what was the maximum length when just positive elements occur. This kind of problem can have applications in data domains. Let's discuss certain ways in which this task can be perform
4 min read
Python - Maximum element in consecutive subsets We are given a list of numbers and a fixed integer k. The task is to determine the maximum number in every consecutive block of k elements. For instance, consider the list [1,3,2,5,4,6,8,7] with k=3. This list can be divided into consecutive subsets: the first subset is [1,3,2], the next is [3,2,5]
3 min read
Python - K consecutive Maximum Given a List, find maximum of next K elements from each index. Input : test_list = [4, 3, 9, 2, 6, 12, 4, 3, 2, 4, 5], K = 4 Output : [9, 9, 9, 12, 12, 12, 4, 5] Explanation : Max of next 4 elements, (max(4, 3, 9, 2) = 9) Input : test_list = [4, 3, 9, 2, 6], K = 4 Output : [9, 9] Explanation : Max o
4 min read
Python | Consecutive Maximum Occurrence in list Sometimes, while working with Python lists or in competitive programming setup, we can come across a subproblem in which we need to get an element which has the maximum consecutive occurrence. The knowledge of the solution of it can be of great help and can be employed whenever required. Let's discu
5 min read