Calculate absolute difference between minimum and maximum sum of pairs in an array | Java 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 ] ; Stores the maximum from the suffix of the array ; Set the last element ; Traverse the remaining array ; Update the maximum from suffix for the remaining indices ; Stores the maximum sum of any pair ; Calculate the maximum sum ; Stores the maximum sum of any pair ; Stores the minimum of suffixes from the given array ; Set the last element ; Traverse the remaining array ; Update the maximum from suffix for the remaining indices ; Calculate the minimum sum ; Return the resultant difference ; Driver Code ; Function Call
import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static int GetDiff ( int A [ ] , int N ) { int SuffMaxArr [ ] = new int [ N ] ; SuffMaxArr [ N - 1 ] = A [ N - 1 ] ; for ( int i = N - 2 ; i >= 0 ; -- i ) { SuffMaxArr [ i ] = Math . max ( SuffMaxArr [ i + 1 ] , A [ i + 1 ] ) ; } int MaximumSum = Integer . MIN_VALUE ; for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( A [ i ] < SuffMaxArr [ i ] ) MaximumSum = Math . max ( MaximumSum , A [ i ] + SuffMaxArr [ i ] ) ; } int MinimumSum = Integer . MAX_VALUE ; int SuffMinArr [ ] = new int [ N ] ; SuffMinArr [ N - 1 ] = Integer . MAX_VALUE ; for ( int i = N - 2 ; i >= 0 ; -- i ) { SuffMinArr [ i ] = Math . min ( SuffMinArr [ i + 1 ] , A [ i + 1 ] ) ; } for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( A [ i ] < SuffMinArr [ i ] ) { MinimumSum = Math . min ( MinimumSum , A [ i ] + SuffMinArr [ i ] ) ; } } return Math . abs ( MaximumSum - MinimumSum ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 4 , 1 , 3 , 7 , 5 , 6 } ; int N = arr . length ; System . out . println ( GetDiff ( arr , N ) ) ; } }