Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Find Maximum difference pair in Python
Data analysis often requires finding pairs of elements with specific characteristics. In this article, we will explore how to find pairs of numbers in a list that have the maximum difference between them using different Python approaches.
Using nlargest() with combinations()
This approach finds all possible combinations of elements, calculates their differences, and uses nlargest() from the heapq module to get multiple pairs with maximum differences.
Example
from itertools import combinations
from heapq import nlargest
numbers = [21, 14, 30, 11, 17, 18]
print("Given list:", numbers)
# Find top 2 pairs with maximum difference
result = nlargest(2, combinations(numbers, 2),
key=lambda pair: abs(pair[0] - pair[1]))
print("Pairs with maximum difference are:", result)
Given list: [21, 14, 30, 11, 17, 18] Pairs with maximum difference are: [(30, 11), (21, 11)]
Using max() with combinations()
This method uses the same combination approach but returns only the single pair with the maximum difference using the max() function.
Example
from itertools import combinations
numbers = [21, 14, 30, 11, 17, 18]
print("Given list:", numbers)
# Find single pair with maximum difference
result = max(combinations(numbers, 2),
key=lambda pair: abs(pair[0] - pair[1]))
print("Pair with maximum difference is:", result)
Given list: [21, 14, 30, 11, 17, 18] Pair with maximum difference is: (30, 11)
Optimized Approach Using min() and max()
For better performance with large lists, we can simply find the minimum and maximum values instead of generating all combinations ?
numbers = [21, 14, 30, 11, 17, 18]
print("Given list:", numbers)
# Find min and max values
min_val = min(numbers)
max_val = max(numbers)
print(f"Pair with maximum difference is: ({max_val}, {min_val})")
print(f"Maximum difference: {max_val - min_val}")
Given list: [21, 14, 30, 11, 17, 18] Pair with maximum difference is: (30, 11) Maximum difference: 19
Comparison
| Method | Time Complexity | Returns | Best For |
|---|---|---|---|
nlargest() |
O(n²) | Multiple pairs | Finding top N pairs |
max() |
O(n²) | Single pair | One maximum pair |
min()/max() |
O(n) | Single pair | Large datasets |
Conclusion
Use combinations() with max() for finding one pair with maximum difference. For multiple pairs, use nlargest(). For optimal performance with large datasets, use the min()/max() approach.
