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 differences between distinct pairs of a triplet from an array
Next article icon

Calculate absolute difference between minimum and maximum sum of pairs in an array

Last Updated : 29 Apr, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] consisting of N integers, the task is to find the absolute difference between the minimum and maximum sum of any pairs of elements (arr[i], arr[j]) such that (i < j) and (arr[i] < arr[j]).

Examples:

Input: arr[] = {1, 2, 4, 7}
Output: 8
Explanation: All possible pairs are:

  • (1, 2) ? Sum = 3
  • (1, 4) ? Sum = 5
  • (1, 7) ? Sum = 8
  • (2, 4) ? Sum = 6
  • (2, 7) ? Sum = 9
  • (4, 7) ? Sum = 11

Therefore, the difference between maximum and minimum sum = 11 - 3 = 8.

Input: arr[] = {2, 5, 3}
Output: 2

Approach: The idea to solve the given problem is to create two auxiliary arrays to store minimum and maximum of suffixes of every index of suffixes of the given array and then find the required absolute difference. 
Follow the steps below to solve the problem:

  • Initialize two variables, say maxSum and minSum, to store the maximum and minimum sum of a pair of elements from the given array according to the given conditions.
  • Initialize two arrays, say suffixMax[] and suffixMin[] of size N, to store the maximum and minimum of suffixes for each index of the array arr[].
  • Traverse the given array arr[] in reverse and update suffixMin[] and suffixMax[] at each index.
  • Now, iterate over the range [0, N - 1] and perform the following steps:
    • If the current element arr[i] is less than suffixMax[i], then update the value of maxSum as the maximum of maxSum and (arr[i] + suffixMax[i]).
    • If the current element arr[i] is less than suffixMin[i], then update the value of minSum as the minimum of minSum and (arr[i] + suffixMin[i]).
  • After completing the above steps, print the value (maxSum - minSum) as the resultant difference.

Below is the implementation of the above approach: 

C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std;  // Function to find the difference between // the maximum and minimum sum of a pair // (arr[i], arr[j]) from the array such // that i < j and arr[i] < arr[j] int GetDiff(int A[], int N) {     // Stores the maximum from     // the suffix of the array     int SuffMaxArr[N];      // Set the last element     SuffMaxArr[N - 1] = A[N - 1];      // Traverse the remaining array     for (int i = N - 2; i >= 0; --i) {          // Update the maximum from suffix         // for the remaining indices         SuffMaxArr[i] = max(SuffMaxArr[i + 1],                             A[i + 1]);     }      // Stores the maximum sum of any pair     int MaximumSum = INT_MIN;      // Calculate the maximum sum     for (int i = 0; i < N - 1; i++) {         if (A[i] < SuffMaxArr[i])             MaximumSum                 = max(MaximumSum,                       A[i] + SuffMaxArr[i]);     }      // Stores the maximum sum of any pair     int MinimumSum = INT_MAX;      // Stores the minimum of suffixes     // from the given array     int SuffMinArr[N];      // Set the last element     SuffMinArr[N - 1] = INT_MAX;      // Traverse the remaining array     for (int i = N - 2; i >= 0; --i) {          // Update the maximum from suffix         // for the remaining indices         SuffMinArr[i] = min(SuffMinArr[i + 1],                             A[i + 1]);     }      // Calculate the minimum sum     for (int i = 0; i < N - 1; i++) {          if (A[i] < SuffMinArr[i]) {             MinimumSum = min(MinimumSum,                              A[i] + SuffMinArr[i]);         }     }      // Return the resultant difference     return abs(MaximumSum - MinimumSum); }  // Driver Code int main() {     int arr[] = { 2, 4, 1, 3, 7, 5, 6 };     int N = sizeof(arr) / sizeof(arr[0]);      // Function Call     cout << GetDiff(arr, N);      return 0; } 
Java
// Java program for the above approach import java.io.*; import java.lang.*; import java.util.*;  class GFG{  // Function to find the difference between // the maximum and minimum sum of a pair // (arr[i], arr[j]) from the array such // that i < j and arr[i] < arr[j] static int GetDiff(int A[], int N) {          // Stores the maximum from     // the suffix of the array     int SuffMaxArr[] = new int[N];      // Set the last element     SuffMaxArr[N - 1] = A[N - 1];      // Traverse the remaining array     for(int i = N - 2; i >= 0; --i)      {                  // Update the maximum from suffix         // for the remaining indices         SuffMaxArr[i] = Math.max(SuffMaxArr[i + 1],                                           A[i + 1]);     }      // Stores the maximum sum of any pair     int MaximumSum = Integer.MIN_VALUE;      // Calculate the maximum sum     for(int i = 0; i < N - 1; i++)      {         if (A[i] < SuffMaxArr[i])             MaximumSum = Math.max(MaximumSum,                                   A[i] + SuffMaxArr[i]);     }      // Stores the maximum sum of any pair     int MinimumSum = Integer.MAX_VALUE;      // Stores the minimum of suffixes     // from the given array     int SuffMinArr[] = new int[N];      // Set the last element     SuffMinArr[N - 1] = Integer.MAX_VALUE;      // Traverse the remaining array     for(int i = N - 2; i >= 0; --i)      {                  // Update the maximum from suffix         // for the remaining indices         SuffMinArr[i] = Math.min(SuffMinArr[i + 1],                                            A[i + 1]);     }      // Calculate the minimum sum     for(int i = 0; i < N - 1; i++)      {         if (A[i] < SuffMinArr[i])         {             MinimumSum = Math.min(MinimumSum,                                   A[i] + SuffMinArr[i]);         }     }      // Return the resultant difference     return Math.abs(MaximumSum - MinimumSum); }  // Driver Code public static void main(String[] args) {     int arr[] = { 2, 4, 1, 3, 7, 5, 6 };     int N = arr.length;      // Function Call     System.out.println(GetDiff(arr, N)); } }  // This code is contributed by Kingash 
Python3
# Python 3 program for the above approach import sys  # Function to find the difference between # the maximum and minimum sum of a pair # (arr[i], arr[j]) from the array such # that i < j and arr[i] < arr[j] def GetDiff(A, N):        # Stores the maximum from     # the suffix of the array     SuffMaxArr = [0 for i in range(N)]      # Set the last element     SuffMaxArr[N - 1] = A[N - 1]      # Traverse the remaining array     i = N-2     while(i >= 0):         # Update the maximum from suffix         # for the remaining indices         SuffMaxArr[i] = max(SuffMaxArr[i + 1], A[i + 1])         i -= 1      # Stores the maximum sum of any pair     MaximumSum = -sys.maxsize-1      # Calculate the maximum sum     for i in range(N-1):         if (A[i] < SuffMaxArr[i]):             MaximumSum = max(MaximumSum, A[i] + SuffMaxArr[i])      # Stores the maximum sum of any pair     MinimumSum = sys.maxsize      # Stores the minimum of suffixes     # from the given array     SuffMinArr = [0 for i in range(N)]      # Set the last element     SuffMinArr[N - 1] = sys.maxsize      # Traverse the remaining array     i = N-2     while(i >= 0):                # Update the maximum from suffix         # for the remaining indices         SuffMinArr[i] = min(SuffMinArr[i + 1], A[i + 1])         i -= 1      # Calculate the minimum sum     for i in range(N - 1):         if (A[i] < SuffMinArr[i]):             MinimumSum = min(MinimumSum,A[i] + SuffMinArr[i])      # Return the resultant difference     return abs(MaximumSum - MinimumSum)  # Driver Code if __name__ == '__main__':     arr = [2, 4, 1, 3, 7, 5, 6]     N = len(arr)          # Function Call     print(GetDiff(arr, N))      # This code is contributed by SURENDRA_GANGWAR. 
C#
// C# Program to implement // the above approach using System;  class GFG  {  // Function to find the difference between // the maximum and minimum sum of a pair // (arr[i], arr[j]) from the array such // that i < j and arr[i] < arr[j] static int GetDiff(int[] A, int N) {          // Stores the maximum from     // the suffix of the array     int[] SuffMaxArr = new int[N];      // Set the last element     SuffMaxArr[N - 1] = A[N - 1];      // Traverse the remaining array     for(int i = N - 2; i >= 0; --i)      {                  // Update the maximum from suffix         // for the remaining indices         SuffMaxArr[i] = Math.Max(SuffMaxArr[i + 1],                                           A[i + 1]);     }      // Stores the maximum sum of any pair     int MaximumSum = Int32.MinValue;      // Calculate the maximum sum     for(int i = 0; i < N - 1; i++)      {         if (A[i] < SuffMaxArr[i])             MaximumSum = Math.Max(MaximumSum,                                   A[i] + SuffMaxArr[i]);     }      // Stores the maximum sum of any pair     int MinimumSum = Int32.MaxValue;      // Stores the minimum of suffixes     // from the given array     int[] SuffMinArr = new int[N];      // Set the last element     SuffMinArr[N - 1] = Int32.MaxValue;      // Traverse the remaining array     for(int i = N - 2; i >= 0; --i)      {                  // Update the maximum from suffix         // for the remaining indices         SuffMinArr[i] = Math.Min(SuffMinArr[i + 1],                                            A[i + 1]);     }      // Calculate the minimum sum     for(int i = 0; i < N - 1; i++)      {         if (A[i] < SuffMinArr[i])         {             MinimumSum = Math.Min(MinimumSum,                                   A[i] + SuffMinArr[i]);         }     }      // Return the resultant difference     return Math.Abs(MaximumSum - MinimumSum); }  // Driver Code public static void Main(String[] args)  {     int[] arr = { 2, 4, 1, 3, 7, 5, 6 };     int N = arr.Length;      // Function Call     Console.WriteLine(GetDiff(arr, N)); } }  // This code is contributed by code_hunt. 
JavaScript
<script> // JavaScript program for the above approach  // Function to find the difference between // the maximum and minimum sum of a pair // (arr[i], arr[j]) from the array such // that i < j and arr[i] < arr[j] function GetDiff(A, N) {           // Stores the maximum from     // the suffix of the array     let SuffMaxArr = Array(N).fill(0);       // Set the last element     SuffMaxArr[N - 1] = A[N - 1];       // Traverse the remaining array     for(let i = N - 2; i >= 0; --i)     {                   // Update the maximum from suffix         // for the remaining indices         SuffMaxArr[i] = Math.max(SuffMaxArr[i + 1],                                           A[i + 1]);     }       // Stores the maximum sum of any pair     let MaximumSum = Number.MIN_VALUE;       // Calculate the maximum sum     for(let i = 0; i < N - 1; i++)     {         if (A[i] < SuffMaxArr[i])             MaximumSum = Math.max(MaximumSum,                                   A[i] + SuffMaxArr[i]);     }       // Stores the maximum sum of any pair     let MinimumSum = Number.MAX_VALUE;       // Stores the minimum of suffixes     // from the given array     let SuffMinArr = Array(N).fill(0);       // Set the last element     SuffMinArr[N - 1] = Number.MAX_VALUE;       // Traverse the remaining array     for(let i = N - 2; i >= 0; --i)     {                   // Update the maximum from suffix         // for the remaining indices         SuffMinArr[i] = Math.min(SuffMinArr[i + 1],                                           A[i + 1]);     }       // Calculate the minimum sum     for(let i = 0; i < N - 1; i++)     {         if (A[i] < SuffMinArr[i])         {             MinimumSum = Math.min(MinimumSum,                                   A[i] + SuffMinArr[i]);         }     }       // Return the resultant difference     return Math.abs(MaximumSum - MinimumSum); }  // Driver Code      let arr = [ 2, 4, 1, 3, 7, 5, 6 ];     let N = arr.length;       // Function Call     document.write(GetDiff(arr, N));      </script> 

Output: 
7

 

Time Complexity: O(N)
Auxiliary Space: O(N)


Next Article
Maximum sum of absolute differences between distinct pairs of a triplet from an array
author
sourav2901
Improve
Article Tags :
  • Algorithms
  • Searching
  • Sorting
  • Mathematical
  • Technical Scripter
  • Competitive Programming
  • DSA
  • Arrays
  • Technical Scripter 2020
  • Suffix
Practice Tags :
  • Algorithms
  • Arrays
  • Mathematical
  • Searching
  • Sorting

Similar Reads

  • 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
  • Count of all pairs in an Array with minimum absolute difference
    Given an integer array arr[] of size N, the task is to count the total number of distinct pairs having minimum absolute difference. Examples: Input: arr[] = {4, 2, 1, 3} Output: 3 Explanation: The minimum absolute difference between the pairs {1, 2}, {2, 3}, {3, 4} is 1.Input: arr[] = {1, 3, 8, 10,
    5 min read
  • Minimum and Maximum sum of absolute differences of pairs
    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, -4
    8 min read
  • Maximum sum of absolute differences between distinct pairs of a triplet from an array
    Given an array arr[] consisting of N integers, the task is to find the maximum sum of absolute differences between all distinct pairs of the triplet in the array. Examples: Input: arr[] = {1, 2, 3, 4}Output: 6Explanation:The valid triplet is (1, 3, 4) as sum = |1 - 4| + |1 - 3| + |3 - 4| = 6, which
    5 min read
  • Find maximum absolute difference with min sum of ratios in an Array
    Given an array of positive integers arr[], the task is to find the maximum absolute difference between the pairs from the array such that the sum of their ratios is minimum. Examples: Input: arr[] = {2, 6, 3, 4, 8, 9}Output: 4Explanation: In the above example, the ratios of every pair are calculated
    7 min read
  • Maximum absolute difference between sum of two contiguous sub-arrays
    Given an array of integers, find two non-overlapping contiguous sub-arrays such that the absolute difference between the sum of two sub-arrays is maximum. Example: Input: [-2, -3, 4, -1, -2, 1, 5, -3] Output: 12 Two subarrays are [-2, -3] and [4, -1, -2, 1, 5] Input: [2, -1, -2, 1, -4, 2, 8] Output:
    15+ 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
  • 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
  • Minimum sum of all differences between unique pairs in the Array
    Given an array arr[] consisting of N integers, the task is to find the minimum sum of all absolute differences between unique pairs of elements in the array after updating the array arr[]. To update the array, any two elements from the array can be chosen in any order. 1 is subtracted from the first
    7 min read
  • Maximum and minimum sum of Bitwise XOR of pairs from an array
    Given an array arr[] of size N, the task is to find the maximum and minimum sum of Bitwise XOR of all pairs from an array by splitting the array into N / 2 pairs. Examples: Input: arr[] = {1, 2, 3, 4}Output: 6 10Explanation:Bitwise XOR of the all possible pair splits are as follows:(1, 2), (3, 4) →
    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