VOOZH about

URL: https://www.geeksforgeeks.org/dsa/calculate-absolute-difference-between-minimum-and-maximum-sum-of-pairs-in-an-array/

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


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 23 Jul, 2025

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: 


Output: 
7

 

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

Comment
Article Tags: