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
Array Partition I in Python
Given an array of 2n integers, we need to group them into n pairs such that the sum of minimum values from each pair is maximized. This is known as the Array Partition I problem.
Problem Understanding
For an array like [1, 2, 3, 4], we can form pairs in different ways ?
(1, 2) and (3, 4) ? min(1, 2) + min(3, 4) = 1 + 3 = 4
(1, 4) and (2, 3) ? min(1, 4) + min(2, 3) = 1 + 2 = 3
(1, 3) and (2, 4) ? min(1, 3) + min(2, 4) = 1 + 2 = 3
The maximum possible sum is 4.
Key Insight
To maximize the sum of minimums, we should sort the array and pair adjacent elements. This ensures that smaller numbers are paired with the next smallest numbers, minimizing the loss of larger values.
Method 1: Direct Sum After Sorting
Sort the array and sum every alternate element starting from index 0 ?
class Solution:
def arrayPairSum(self, nums):
nums.sort()
result = 0
for i in range(0, len(nums), 2):
result += nums[i]
return result
# Example
solution = Solution()
arr = [1, 4, 3, 2]
print("Array:", arr)
print("Maximum sum:", solution.arrayPairSum(arr))
Array: [1, 4, 3, 2] Maximum sum: 4
Method 2: Using List Comprehension
A more Pythonic approach using list comprehension ?
class Solution:
def arrayPairSum(self, nums):
nums.sort()
return sum(nums[i] for i in range(0, len(nums), 2))
# Example
solution = Solution()
arr = [6, 2, 6, 5, 1, 2]
print("Array:", arr)
print("Maximum sum:", solution.arrayPairSum(arr))
Array: [6, 2, 6, 5, 1, 2] Maximum sum: 9
Method 3: Explicit Pair Formation
Create pairs explicitly and then sum their minimums ?
class Solution:
def arrayPairSum(self, nums):
nums.sort()
pairs = []
for i in range(0, len(nums), 2):
pairs.append((nums[i], nums[i + 1]))
return sum(min(pair) for pair in pairs)
# Example
solution = Solution()
arr = [7, 8, 6, 9]
print("Array:", arr)
print("Sorted pairs:", [(arr[i], arr[i+1]) for i in range(0, len(sorted(arr)), 2)])
print("Maximum sum:", solution.arrayPairSum(arr))
Array: [7, 8, 6, 9] Sorted pairs: [(6, 7), (8, 9)] Maximum sum: 14
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Direct Sum | O(n log n) | O(1) | Memory efficiency |
| List Comprehension | O(n log n) | O(1) | Readable code |
| Explicit Pairs | O(n log n) | O(n) | Understanding pairs |
How It Works
The algorithm works because after sorting, pairing adjacent elements ensures that each smaller element is paired with the next available larger element, maximizing the contribution of smaller values to the final sum.
Conclusion
Sort the array and sum elements at even indices for the optimal solution. The key insight is that sorting minimizes the loss of larger values when taking minimums from pairs.
