Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Maximum sum of absolute difference of any permutation
Next article icon

Minimum and Maximum sum of absolute differences of pairs

Last Updated : 20 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array of N integers where N is even, find the minimum and maximum sum of absolute difference of N/2 pairs formed by pairing every element with one other element.

Examples: 

Input: a[] = {10, -10, 20, -40}  Output: min_sum = 40, max_sum = 80 Explanation: Pairs selected for minimum sum               (-10, -40) and (10, 20)               min_sum = |-10 - -40| + |20 - 10| = 40               Pairs selected for maximum sum               (-10, 20) and (-40, 10)               max_sum = |-10 - 20| + |10 - -40| = 80  Input: a[] = {20, -10, -1, 30}  Output: min_sum = 19, max_sum = 61  Explanation: Pairs selected for minimum sum              (-1, -10) and (20, 30)               min_sum = |-1 - -10| + |20 - 30| = 19               Pairs selected for maximum sum              (-1, 30) and (-10, 20)               max_sum = |-1 - 30| + |-10 - 20| = 61 

Approach: The most common observation will be that for minimum sum of differences we need the closest elements together as a pair and for the maximum sum we need the farthest elements together as a pair. So, we can simply sort the given list of elements and the closest pairs will be a[i], a[i+1], their absolute difference sum will yield us the minimum sum. The farthest will be (a[0], a[n-1]) and (a[1], a[n-2]) and so on, and their absolute difference sum will yield us the maximum-sum.

Implementation:

C++




// CPP program to find minimum and maximum
// sum of absolute differences of pairs
#include <bits/stdc++.h>
using namespace std;
 
// function to calculate minimum sum
int calculate_min_sum(int a[], int n)
{
    // sorts the array c++ stl
    sort(a, a + n);
 
    // initially min=0 and max=0
    int min_sum = 0;
 
    // traverse to find the minimum sum
    for (int i = 1; i < n; i += 2) {
 
        // the adjacent elements difference
        // will always be smaller
        min_sum += abs(a[i] - a[i - 1]);
    }
    return min_sum;
}
 
// function to calculate maximum sum
int calculate_max_sum(int a[], int n)
{
    // sorts the array c++ stl
    sort(a, a + n);
 
    int max_sum = 0;
 
    // traverse to find the maximum sum
    for (int i = 0; i < n / 2; i++) {
         
        // the farthest distant elements sum
        // will always be maximum
        max_sum += abs(a[n - 1 - i] - a[i]);
    }
    return max_sum;
}
 
// Driver program to test above function
int main()
{
    int a[] = { 10, -10, 20, -40};
 
    int n = sizeof(a) / sizeof(a[0]);
 
    cout << "The minimum sum of pairs is "
         << calculate_min_sum(a, n) << endl;
 
    cout << "The maximum sum of pairs is "
         << calculate_max_sum(a, n) << endl;
 
    return 0;
}
 
 

Java




// Java program to find minimum and maximum
// sum of absolute differences of pairs
import java.util.Arrays;
 
class GFG
{
    // function to calculate minimum sum
    static int calculate_min_sum(int[] a, int n)
    {
        // sorts the array c++ stl
        Arrays.sort(a);
 
        // initially min=0 and max=0
        int min_sum = 0;
 
        // traverse to find the minimum sum
        for (int i = 1; i < n; i += 2) {
 
            // the adjacent elements difference
            // will always be smaller
            min_sum += Math.abs(a[i] - a[i - 1]);
        }
        return min_sum;
    }
 
    // function to calculate maximum sum
    static int calculate_max_sum(int[] a, int n)
    {
        // sorts the array c++ stl
        Arrays.sort(a);
 
        int max_sum = 0;
 
        // traverse to find the maximum sum
        for (int i = 0; i < n / 2; i++) {
         
            // the farthest distant elements sum
            // will always be maximum
            max_sum += Math.abs(a[n - 1 - i] - a[i]);
        }
        return max_sum;
    }
 
    // Driver program to test above function   
    public static void main (String[] args) {
    int[] a = { 10, -10, 20, -40};
 
    int n = a.length;
     
    System.out.println("The minimum sum of pairs is " +
                          calculate_min_sum(a, n));
 
    System.out.println("The maximum sum of pairs is " +
                           calculate_max_sum(a, n));
     
    }
}
 
/* This code is contributed by Mr. Somesh Awasthi */
 
 

Python3




# Python 3 program to find minimum and maximum
# sum of absolute differences of pairs
 
# function to calculate minimum sum
def calculate_min_sum( a, n):
 
    # sorts the array c++ stl
    a.sort()
 
    # initially min=0 and max=0
    min_sum = 0
 
    # traverse to find the minimum sum
    for i in range(1, n, 2):
 
        # the adjacent elements difference
        # will always be smaller
        min_sum += abs(a[i] - a[i - 1])
     
    return min_sum
 
# function to calculate maximum sum
def calculate_max_sum(a, n):
 
    # sorts the array c++ stl
    a.sort()
 
    max_sum = 0
 
    # traverse to find the maximum sum
    for i in range(n // 2):
         
        # the farthest distant elements sum
        max_sum += abs(a[n - 1 - i] - a[i])
    return max_sum
 
# Driver Code
if __name__ == "__main__":
     
    a = [ 10, -10, 20, -40]
 
    n = len(a)
 
    print("The minimum sum of pairs is",
                calculate_min_sum(a, n))
 
    print( "The maximum sum of pairs is",
                 calculate_max_sum(a, n))
 
# This code is contributed by ita_c
 
 

C#




// C# program to find minimum and maximum
// sum of absolute differences of pairs
using System;
 
class GFG
{
    // function to calculate minimum sum
    static int calculate_min_sum(int []a, int n)
    {
        // sorts the array c++ stl
        Array.Sort(a);
 
        // initially min=0 and max=0
        int min_sum = 0;
 
        // traverse to find the minimum sum
        for (int i = 1; i < n; i += 2) {
 
            // the adjacent elements difference
            // will always be smaller
            min_sum += Math.Abs(a[i] - a[i - 1]);
        }
        return min_sum;
    }
 
    // Function to calculate maximum sum
    static int calculate_max_sum(int []a, int n)
    {
        // sorts the array c++ stl
        Array.Sort(a);
 
        int max_sum = 0;
 
        // Traverse to find the maximum sum
        for (int i = 0; i < n / 2; i++) {
         
            // the farthest distant elements sum
            // will always be maximum
            max_sum += Math.Abs(a[n - 1 - i] - a[i]);
        }
        return max_sum;
    }
 
    // Driver Code
    public static void Main ()
    {
    int []a = { 10, -10, 20, -40};
 
    int n = a.Length;
     
    Console.WriteLine("The minimum sum of pairs is " +
                            calculate_min_sum(a, n));
 
    Console.Write("The maximum sum of pairs is " +
                         calculate_max_sum(a, n));
     
    }
}
 
// This code is contributed by nitin mittal.
 
 

PHP




<?php
// PHP program to find minimum and maximum
// sum of absolute differences of pairs
 
// function to calculate minimum sum
function calculate_min_sum($a, $n)
{
     
    // sorts the array c++ stl
    sort($a);
 
    // initially min=0 and max=0
    $min_sum = 0;
 
    // traverse to find the minimum sum
    for ($i = 1; $i < $n; $i += 2)
    {
 
        // the adjacent elements difference
        // will always be smaller
        $min_sum += abs($a[$i] -
                    $a[$i - 1]);
    }
    return $min_sum;
}
 
// function to calculate maximum sum
function calculate_max_sum($a, $n)
{
     
    // sorts the array c++ stl
    sort($a);
 
    $max_sum = 0;
 
    // traverse to find the maximum sum
    for ($i = 0; $i < $n / 2; $i++)
    {
         
        // the farthest distant elements sum
        // will always be maximum
        $max_sum += abs($a[$n - 1 - $i] -
                                  $a[$i]);
    }
    return $max_sum;
}
 
// Driver Code
$a = array(10, -10, 20, -40);
 
$n = sizeof($a);
 
echo("The minimum sum of pairs is "
        . calculate_min_sum($a, $n) . "\n");
 
echo("The maximum sum of pairs is "
        . calculate_max_sum($a, $n));
 
// This code is contributed by Ajit.
?>
 
 

Javascript




<script>
 
// Javascript program to find minimum and maximum
// sum of absolute differences of pairs
 
// Function to calculate minimum sum
function calculate_min_sum(a, n)
{
     
    // Sorts the array c++ stl
    a.sort();
 
    // Initially min=0 and max=0
    let min_sum = 0;
 
    // Traverse to find the minimum sum
    for(let i = 1; i < n; i += 2)
    {
         
        // The adjacent elements difference
        // will always be smaller
        min_sum += Math.abs(a[i] - a[i - 1]);
    }
    return min_sum;
}
 
// Function to calculate maximum sum
function calculate_max_sum(a, n)
{
     
    // Sorts the array c++ stl
    a.sort();
 
    let max_sum = 0;
 
    // Traverse to find the maximum sum
    for(let i = 0; i < parseInt(n / 2, 10); i++)
    {
         
        // The farthest distant elements sum
        // will always be maximum
        max_sum += Math.abs(a[n - 1 - i] - a[i]);
    }
    return max_sum;
}
 
// Driver code
let a = [ 10, -10, 20, -40 ];
let n = a.length;
   
document.write("The minimum sum of pairs is " +
               calculate_min_sum(a, n) + "</br>");
 
document.write("The maximum sum of pairs is " +
               calculate_max_sum(a, n));
                
// This code is contributed by decode2207
 
</script>
 
 
Output
The minimum sum of pairs is 40 The maximum sum of pairs is 80

Time complexity : O(n log n)

 



Next Article
Maximum sum of absolute difference of any permutation
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • Arrays
  • DSA
Practice Tags :
  • Arrays

Similar Reads

  • Sum of absolute difference of maximum and minimum of all subarrays
    Given an array arr containing N integers, the task is to find the sum of the absolute difference of maximum and minimum of all subarrays. Example: Input: arr[] = {1, 4, 3}Output: 7Explanation: The following are the six subarrays:[1] : maximum - minimum= 1 - 1 = 0[4] : maximum - minimum= 4 - 4 = 0[3]
    5 min read
  • Maximum sum of absolute difference of any permutation
    Given an array, we need to find the maximum sum of the absolute difference of any permutation of the given array. Examples: Input : { 1, 2, 4, 8 } Output : 18 Explanation : For the given array there are several sequence possible like : {2, 1, 4, 8} {4, 2, 1, 8} and some more. Now, the absolute diffe
    14 min read
  • Minimum sum of absolute difference of pairs of two arrays
    Given two arrays a[] and b[] of equal length n. The task is to pair each element of array a to an element in array b, such that sum S of absolute differences of all the pairs is minimum.Suppose, two elements a[i] and a[j] (i != j) of a are paired with elements b[p] and b[q] of b respectively, then p
    7 min read
  • Sum of minimum absolute differences in an array
    Given an array of n distinct integers. The task is to find the sum of minimum absolute difference of each array element. For an element arr[i] present at index i in the array, its minimum absolute difference is calculated as: Min absolute difference (arr[i]) = min(abs(arr[i] - arr[j])), where 0 <
    8 min read
  • Minimum value of maximum absolute difference of all adjacent pairs in an Array
    Given an array arr, containing non-negative integers and (-1)s, of size N, the task is to replace those (-1)s with a common non-negative integer such that the maximum absolute difference of all adjacent pairs is minimum. Print this minimum possible value of the maximum absolute difference. Examples:
    9 min read
  • Minimum possible sum of absolute difference of pairs from given arrays
    Given two arrays a[] and b[] of size N and M respectively (N < M), the task is to find the minimum possible sum of absolute difference of pairs formed by pairing each element of array a[] with an element of array b[] Note: Each element of each array can be considered only once. Examples: Input: a
    8 min read
  • Sum of absolute differences of all pairs in a given array
    Given a sorted array of distinct elements, the task is to find the summation of absolute differences of all pairs in the given array. Examples: Input : arr[] = {1, 2, 3, 4} Output: 10 Sum of |2-1| + |3-1| + |4-1| + |3-2| + |4-2| + |4-3| = 10 Input : arr[] = {1, 8, 9, 15, 16} Output: 74 Input : arr[]
    11 min read
  • Subsequence with maximum pairwise absolute difference and minimum size
    Given an array arr[] of N integers, the task is to print the subsequence from the given array with the maximum pairwise absolute difference of adjacent elements. If multiple such subsequences exist, then print the subsequence with the smallest length. Examples: Input: arr[] = {1, 2, 4, 3, 5} Output:
    7 min read
  • Maximum sum of minimums of pairs in an array
    Given an array arr[] of N integers where N is even, the task is to group the array elements in the pairs (X1, Y1), (X2, Y2), (X3, Y3), ... such that the sum min(X1, Y1) + min(X2, Y2) + min(X3, Y3) + ... is maximum.Examples: Input: arr[] = {1, 5, 3, 2} Output: 4 (1, 5) and (3, 2) -> 1 + 2 = 3 (1,
    4 min read
  • Minimum sum of absolute differences of pairs in a triplet from three arrays
    Given three arrays a[], b[] and c[] of sizes A, B and C respectively, the task is to find the minimum possible value of abs(a[i] - b[j]) + abs(b[j] - c[k]) where 0 ? i ? A, 0 ? j ? B and 0 ? k ? C. Examples: Input: A = 3, B = 2, C = 2, a[] = {1, 8, 5}, b[] = {2, 9}, c[] = {5, 4}Output: 3Explanation:
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences