![]() |
VOOZH | about |
Sometimes, while working with data, we might have a problem in which we need to find maximum difference 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 absolute difference of all pairs and then return the max of it using max().
The original list : [(3, 5), (1, 7), (10, 3), (1, 2)] Maximum difference among pairs : 7
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 difference computation logic. Returns the max. difference pair.
The original list : [(3, 5), (1, 7), (10, 3), (1, 2)] Maximum difference among pairs : (10, 3)
Method #3: Using reduce() function and a lambda function
This approach uses the reduce() function to iterate through the elements of the list and a lambda function to compute the maximum difference between the elements of each tuple.
The original list : [(3, 5), (1, 7), (10, 3), (1, 2)] Maximum difference among pairs : (10, 3)
The time complexity of this method is also O(n) and Auxiliary space is O(1) as well.
Method 4 : using a for loop:
This code iterates over each pair in the list and compares the absolute difference of each pair to the maximum difference seen so far. If the absolute difference of the current pair is greater than the maximum difference seen so far, then the current pair becomes the new max_pair.
step by step approach of the code you provided:
The original list : [(3, 5), (1, 7), (10, 3), (1, 2)] Maximum difference among pairs : (10, 3)
The time complexity of this approach is O(n) since it iterates over the list once.
The space complexity is O(1) since it only stores a constant number of variables (max_pair and max_diff).
Method #5: Using map() and abs() with key argument
Maximum difference among pairs : (10, 3)
Time complexity: O(n), where n is the length of test_list
Auxiliary space: O(n), where n is the length of test_list