![]() |
VOOZH | about |
Sometimes, while working with data, we might have a problem in which we need to find maximum product between available pairs in list. This can be application to many problems in mathematics domain. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using max() + list comprehension The combination of this functions can be used to perform this task. In this, we compute the product of all pairs and then return the max of it using max().
The original list : [(3, 5), (1, 7), (10, 3), (1, 2)] Maximum product among pairs : 30
Time Complexity: O(n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(1), constant extra space is required
Method #2 : Using max() + lambda This is similar to above method. In this the task performed by list comprehension is solved using lambda function, providing the product computation logic. Returns the max. product pair.
The original list : [(3, 5), (1, 7), (10, 3), (1, 2)] Maximum product among pairs : 30
Method 3 : Here is another approach using the reduce function from the functools library:
The original list : [(3, 5), (1, 7), (10, 3), (1, 2)] Maximum Product among pairs : 30
This code uses the reduce function to reduce the list to a single tuple which has the maximum product. The lambda function takes in two tuples and compares their product, returning the tuple with the larger product. This process is repeated until a single tuple with the maximum product is left.
Time complexity: O(n)
Space complexity: O(1)
Method #4: Using a loop and comparison
Initialize two variables, max_product and current_product, to 0.
Loop through each tuple in the list.
Calculate the product of the tuple elements and store it in current_product.
If current_product is greater than max_product, set max_product to current_product.
After the loop ends, print the value of max_product.
The original list : [(3, 5), (1, 7), (10, 3), (1, 2)] Maximum Product among pairs : 30
Time complexity: O(n), where n is the number of tuples in the list.
Auxiliary space: O(1)
Method #5 : Using the itertools module
The original list: [(3, 5), (1, 7), (10, 3), (1, 2)] Maximum Product among pairs: 30
Time complexity: O(n^2).
Auxiliary Space: O(1)