Find sum of difference of maximum and minimum over all possible subsets of size K
Last Updated :
23 Jul, 2025
Given an array arr[] of N integers and an integer K, the task is to find the sum of the difference between the maximum and minimum elements over all possible subsets of size K.
Examples:
Input: arr[] = {1, 1, 3, 4}, K = 2
Output: 11
Explanation:
There are 6 subsets of the given array of size K(= 2). They are {1, 1}, {1, 3}, {1, 4}, {1, 3}, {1, 4} and {3, 4}.
The values of maximum - minimum for each of the subsets respectively are 0, 2, 3, 2, 3, 1 and their sum is 11.
Input: arr[] = {1, 1, 1}, K = 1
Output: 0
Approach: The given problem can be solved based on the following observations:
- The sum of the difference between maximum and minimum from all the sets is independent of each other, i.e, it can be calculated as the sum of maximum from all sets of size K - the sum of minimum from all sets of size K.
- In a sorted array arr[], arr[i] is the maximum of all sets having elements from the array in the range [0, i - 1]. Therefore, the number of sets of size K having arr[i] as the maximum array element can be calculated as {}^{i}C_{K - 1} . Similarly, the number of sets of size K having arr[i] as the minimum element are {}^{N - i - 1}C_{K - 1} .
- The value of {}^{N}C_{R} can be calculated efficiently by using the approach discussed in this article.
Using the above observations, the given problem can be solved by following the below steps:
- Sort the given array arr[] in non-decreasing order.
- In order to calculate the sum of the maximum of all sets of size K, create a variable sumMax, and for each, the index i in the range [K - 1, N - 1], iterate through the array arr[] and add arr[i] * {}^{i}C_{K - 1} into sumMax.
- Similarly, In order to calculate the sum of the minimum of all sets of size K, create a variable sumMin and for each i in the range [0, N-K], iterate through the array arr[] and add arr[i] * {}^{N - i - 1}C_{K - 1} into sumMin.
- The value of sumMax - sumMin is the required answer.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
#define int long long int
#define max 100000
#define mod 1000000007
int inv[max], fact[max], facinv[max];
// Function to precompute factorial and
// the inverse of factorial values of all
// elements in the range [1, max] to find
// the value of nCr in O(1)
void ncrPrecomputation()
{
inv[0] = inv[1] = 1;
fact[0] = fact[1] = 1;
facinv[0] = facinv[1] = 1;
// Loop to iterate over all i in
// the range [2, max]
for (int i = 2; i < max; i++) {
// Calculate Inverse of i
inv[i] = inv[mod % i]
* (mod - mod / i) % mod;
// Calculate Factorial of i
fact[i] = (fact[i - 1] * i) % mod;
// Calculate the Inverse of
// factorial of i
facinv[i] = (inv[i] * facinv[i - 1]) % mod;
}
}
// Function to find nCr in O(1)
int nCr(int n, int r)
{
return ((fact[n] * facinv[r]) % mod
* facinv[n - r])
% mod;
}
// Function to find the sum of difference
// between maximum and minimum over all
// sets of arr[] having K elements
int sumMaxMin(int arr[], int N, int K)
{
// Sort the given array
sort(arr, arr + N);
// Stores the sum of maximum of
// all the sets
int sumMax = 0;
// Loop to iterate arr[] in the
// range [K-1, N-1]
for (int i = K - 1; i < N; i++) {
// Add sum of sets having arr[i]
// as the maximum element
sumMax += (arr[i] * nCr(i, K - 1));
}
// Stores the sum of the minimum of
// all the sets
int sumMin = 0;
// Loop to iterate arr[] in the
// range [0, N - K]
for (int i = 0; i <= N - K; i++) {
// Add sum of sets having arr[i]
// as the minimum element
sumMin += (arr[i] * nCr(N - i - 1, K - 1));
}
// Return answer
return (sumMax - sumMin);
}
// Driver Code
signed main()
{
int arr[] = { 1, 1, 3, 4 };
int K = 2;
int N = sizeof(arr) / sizeof(arr[0]);
ncrPrecomputation();
cout << sumMaxMin(arr, N, K);
return 0;
}
Java
// Java program for the above approach
import java.io.*;
import java.util.*;
class GFG {
static final int max = 100000;
static final int mod = 1000000007;
static long inv[] = new long[max], fact[] = new long[max],
facinv[] = new long[max];
// Function to precompute factorial and
// the inverse of factorial values of all
// elements in the range [1, max] to find
// the value of nCr in O(1)
static void ncrPrecomputation()
{
inv[0] = inv[1] = 1;
fact[0] = fact[1] = 1;
facinv[0] = facinv[1] = 1;
// Loop to iterate over all i in
// the range [2, max]
for (int i = 2; i < max; i++) {
// Calculate Inverse of i
inv[i] = inv[mod % i] * (mod - mod / i) % mod;
// Calculate Factorial of i
fact[i] = (fact[i - 1] * i) % mod;
// Calculate the Inverse of
// factorial of i
facinv[i] = (inv[i] * facinv[i - 1]) % mod;
}
}
// Function to find nCr in O(1)
static long nCr(long n, long r)
{
return ((fact[(int)n] * facinv[(int)r]) % mod * facinv[(int)(n - r)])
% mod;
}
// Function to find the sum of difference
// between maximum and minimum over all
// sets of arr[] having K elements
static long sumMaxMin(long arr[], long N, long K)
{
// Sort the given array
Arrays.sort(arr);
// Stores the sum of maximum of
// all the sets
long sumMax = 0;
// Loop to iterate arr[] in the
// range [K-1, N-1]
for (int i = (int)K - 1; i < N; i++) {
// Add sum of sets having arr[i]
// as the maximum element
sumMax += (arr[i] * nCr(i, K - 1));
}
// Stores the sum of the minimum of
// all the sets
long sumMin = 0;
// Loop to iterate arr[] in the
// range [0, N - K]
for (int i = 0; i <= N - K; i++) {
// Add sum of sets having arr[i]
// as the minimum element
sumMin += (arr[i] * nCr(N - i - 1, K - 1));
}
// Return answer
return (sumMax - sumMin);
}
// Driver Code
public static void main(String[] args)
{
long arr[] = { 1, 1, 3, 4 };
long K = 2;
long N = arr.length;
ncrPrecomputation();
System.out.println(sumMaxMin(arr, N, K));
}
}
// This code is contributed by Dharanendra L V.
C#
// C# program for the above approach
using System;
public class GFG
{
static readonly int max = 100000;
static readonly int mod = 1000000007;
static long []inv = new long[max];
static long []fact = new long[max];
static long []facinv = new long[max];
// Function to precompute factorial and
// the inverse of factorial values of all
// elements in the range [1, max] to find
// the value of nCr in O(1)
static void ncrPrecomputation()
{
inv[0] = inv[1] = 1;
fact[0] = fact[1] = 1;
facinv[0] = facinv[1] = 1;
// Loop to iterate over all i in
// the range [2, max]
for (int i = 2; i < max; i++) {
// Calculate Inverse of i
inv[i] = inv[mod % i] * (mod - mod / i) % mod;
// Calculate Factorial of i
fact[i] = (fact[i - 1] * i) % mod;
// Calculate the Inverse of
// factorial of i
facinv[i] = (inv[i] * facinv[i - 1]) % mod;
}
}
// Function to find nCr in O(1)
static long nCr(long n, long r)
{
return ((fact[(int)n] * facinv[(int)r]) % mod * facinv[(int)(n - r)])
% mod;
}
// Function to find the sum of difference
// between maximum and minimum over all
// sets of []arr having K elements
static long sumMaxMin(long []arr, long N, long K)
{
// Sort the given array
Array.Sort(arr);
// Stores the sum of maximum of
// all the sets
long sumMax = 0;
// Loop to iterate []arr in the
// range [K-1, N-1]
for (int i = (int)K - 1; i < N; i++) {
// Add sum of sets having arr[i]
// as the maximum element
sumMax += (arr[i] * nCr(i, K - 1));
}
// Stores the sum of the minimum of
// all the sets
long sumMin = 0;
// Loop to iterate []arr in the
// range [0, N - K]
for (int i = 0; i <= N - K; i++) {
// Add sum of sets having arr[i]
// as the minimum element
sumMin += (arr[i] * nCr(N - i - 1, K - 1));
}
// Return answer
return (sumMax - sumMin);
}
// Driver Code
public static void Main(String[] args)
{
long []arr = { 1, 1, 3, 4 };
long K = 2;
long N = arr.Length;
ncrPrecomputation();
Console.WriteLine(sumMaxMin(arr, N, K));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python 3 program for the above approach
max1 = 100000
mod = 1000000007
inv = [0 for i in range(max1)]
fact = [0 for i in range(max1)]
facinv = [0 for i in range(max1)]
# Function to precompute factorial and
# the inverse of factorial values of all
# elements in the range [1, max] to find
# the value of nCr in O(1)
def ncrPrecomputation():
inv[0] = inv[1] = 1
fact[0] = fact[1] = 1
facinv[0] = facinv[1] = 1
# Loop to iterate over all i in
# the range [2, max]
for i in range(2,max1,1):
# Calculate Inverse of i
inv[i] = inv[mod % i] * (mod - mod // i) % mod
# Calculate Factorial of i
fact[i] = (fact[i - 1] * i) % mod
# Calculate the Inverse of
# factorial of i
facinv[i] = (inv[i] * facinv[i - 1]) % mod
# Function to find nCr in O(1)
def nCr(n,r):
return ((fact[n] * facinv[r]) % mod * facinv[n - r]) % mod
# Function to find the sum of difference
# between maximum and minimum over all
# sets of arr[] having K elements
def sumMaxMin(arr, N, K):
# Sort the given array
arr.sort()
# Stores the sum of maximum of
# all the sets
sumMax = 0
# Loop to iterate arr[] in the
# range [K-1, N-1]
for i in range(K - 1,N,1):
# Add sum of sets having arr[i]
# as the maximum element
sumMax += (arr[i] * nCr(i, K - 1))
# Stores the sum of the minimum of
# all the sets
sumMin = 0
# Loop to iterate arr[] in the
# range [0, N - K]
for i in range(N - K+1):
# Add sum of sets having arr[i]
# as the minimum element
sumMin += (arr[i] * nCr(N - i - 1, K - 1))
# Return answer
return (sumMax - sumMin)
# Driver Code
if __name__ == '__main__':
arr = [1, 1, 3, 4]
K = 2
N = len(arr)
ncrPrecomputation()
print(sumMaxMin(arr, N, K))
# This code is contributed by SURENDRA_GANGWAR
JavaScript
<script>
// JaVASCRIPT program for the above approach
let max = 100000;
let mod = 1000000007;
let inv = new Array(max).fill(0),
fact = new Array(max).fill(0),
facinv = new Array(max).fill(0);
// Function to precompute factorial and
// the inverse of factorial values of all
// elements in the range [1, max] to find
// the value of nCr in O(1)
function ncrPrecomputation() {
inv[0] = inv[1] = 1;
fact[0] = fact[1] = 1;
facinv[0] = facinv[1] = 1;
// Loop to iterate over all i in
// the range [2, max]
for (let i = 2; i < max; i++) {
// Calculate Inverse of i
inv[i] = (inv[mod % i] * Math.ceil(mod - mod / i)) % mod;
// Calculate Factorial of i
fact[i] = (fact[i - 1] * i) % mod;
// Calculate the Inverse of
// factorial of i
facinv[i] = (inv[i] * facinv[i - 1]) % mod;
}
}
// Function to find nCr in O(1)
function nCr(n, r) {
return (((fact[n] * facinv[r]) % mod) * facinv[n - r]) % mod;
}
// Function to find the sum of difference
// between maximum and minimum over all
// sets of arr[] having K elements
function sumMaxMin(arr, N, K) {
// Sort the given array
arr.sort((a, b) => a - b);
// Stores the sum of maximum of
// all the sets
let sumMax = 0;
// Loop to iterate arr[] in the
// range [K-1, N-1]
for (let i = K - 1; i < N; i++) {
// Add sum of sets having arr[i]
// as the maximum element
sumMax += arr[i] * nCr(i, K - 1);
}
// Stores the sum of the minimum of
// all the sets
let sumMin = 0;
// Loop to iterate arr[] in the
// range [0, N - K]
for (let i = 0; i <= N - K; i++) {
// Add sum of sets having arr[i]
// as the minimum element
sumMin += arr[i] * nCr(N - i - 1, K - 1);
}
// Return answer
return sumMax - sumMin;
}
// Driver Code
let arr = [1, 1, 3, 4];
let K = 2;
let N = arr.length;
ncrPrecomputation();
document.write(sumMaxMin(arr, N, K));
// This code is contributed by saurabh_jaiswal.
</script>
Time Complexity: O(N*log N)
Auxiliary Space: O(N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem