
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Find the sum of maximum difference possible from all subset of a given array in Python
Suppose we have an array A of n values (elements may not be distinct). We have to find the sum of maximum difference possible from all subsets of given array. Now consider max(s) denotes the maximum value in any subset, and min(s) denotes the minimum value in the set. We have to find the sum of max(s)-min(s) for all possible subsets.
So, if the input is like A = [1, 3, 4], then the output will be 9.
To solve this, we will follow these steps −
n := size of A
sort the list A
sum_min := 0, sum_max := 0
for i in range 0 to n, do
sum_max := 2 * sum_max + A[n-1-i]
sum_max := sum_max mod N
sum_min := 2 * sum_min + A[i]
sum_min := sum_min mod N
return(sum_max - sum_min + N) mod N
Example
Let us see the following implementation to get better understanding −
N = 1000000007 def get_max_min_diff(A): n = len(A) A.sort() sum_min = 0 sum_max = 0 for i in range(0,n): sum_max = 2 * sum_max + A[n-1-i] sum_max %= N sum_min = 2 * sum_min + A[i] sum_min %= N return (sum_max - sum_min + N) % N A = [1, 3, 4] print(get_max_min_diff(A))
Input
[1, 3, 4]
Output
9
- Related Articles
- Program to find sum of the 2 power sum of all subarray sums of a given array in Python
- Program to find maximum possible population of all the cities in python
- Maximum size subset with given sum in C++
- Program to find the maximum score from all possible valid paths in Python
- Find the smallest positive integer value that cannot be represented as sum of any subset of a given array in Python
- Maximum sum of i * arr[i] among all rotations of a given array in C++
- Find Sum of all unique subarray sum for a given array in C++
- How to find all possible permutations of a given string in Python?
- How to find the sum of all elements of a given array in JavaScript?
- Find a pair from the given array with maximum nCr value in Python
- Find maximum sum possible equal sum of three stacks in C++
- Check if is possible to get given sum from a given set of elements in Python
- Maximum possible difference of two subsets of an array in C++
- Find all possible outcomes of a given expression in C++
- Find maximum height pyramid from the given array of objects in C++

Advertisements