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 the sum of maximum difference possible from all subset of a given array in Python
Given an array of n values, we need to find the sum of maximum differences possible from all subsets. For each subset, we calculate max(subset) - min(subset), then sum these differences across all possible subsets.
For example, if we have array [1, 3, 4], the subsets and their max-min differences are:
{1}: max=1, min=1, difference=0
{3}: max=3, min=3, difference=0
{4}: max=4, min=4, difference=0
{1,3}: max=3, min=1, difference=2
{1,4}: max=4, min=1, difference=3
{3,4}: max=4, min=3, difference=1
{1,3,4}: max=4, min=1, difference=3
Total sum = 0+0+0+2+3+1+3 = 9
Algorithm Approach
Instead of generating all subsets, we use a mathematical approach:
Sort the array to identify contribution patterns
Calculate sum of maximum values across all subsets (sum_max)
Calculate sum of minimum values across all subsets (sum_min)
Return sum_max - sum_min
Implementation
def get_max_min_diff(A):
N = 1000000007
n = len(A)
A.sort()
sum_min = 0
sum_max = 0
for i in range(n):
# A[n-1-i] contributes as maximum in 2^i subsets
sum_max = (2 * sum_max + A[n-1-i]) % N
# A[i] contributes as minimum in 2^i subsets
sum_min = (2 * sum_min + A[i]) % N
return (sum_max - sum_min + N) % N
# Test with example
A = [1, 3, 4]
result = get_max_min_diff(A)
print(f"Array: {A}")
print(f"Sum of max differences: {result}")
Array: [1, 3, 4] Sum of max differences: 9
How It Works
After sorting the array, each element A[i] appears as minimum in exactly 2^i subsets, and each element A[n-1-i] appears as maximum in exactly 2^i subsets. We calculate these contributions efficiently using the iterative formula.
Example with Larger Array
# Test with more elements
A = [2, 1, 4, 9]
result = get_max_min_diff(A)
print(f"Array: {A}")
print(f"Sum of max differences: {result}")
# Show sorted array for clarity
A_sorted = sorted(A)
print(f"Sorted array: {A_sorted}")
Array: [2, 1, 4, 9] Sum of max differences: 56 Sorted array: [1, 2, 4, 9]
Time and Space Complexity
Time Complexity: O(n log n) due to sorting
Space Complexity: O(1) excluding input array
Conclusion
This algorithm efficiently calculates the sum of maximum differences across all subsets using mathematical properties instead of generating all 2^n subsets. The key insight is that after sorting, each element's contribution as maximum or minimum follows a predictable pattern.
