Calculate absolute difference between minimum and maximum sum of pairs in an array | C # Program to implement 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
using System ; 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 = Int32 . MinValue ; for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( A [ i ] < SuffMaxArr [ i ] ) MaximumSum = Math . Max ( MaximumSum , A [ i ] + SuffMaxArr [ i ] ) ; } int MinimumSum = Int32 . MaxValue ; int [ ] SuffMinArr = new int [ N ] ; SuffMinArr [ N - 1 ] = Int32 . MaxValue ; 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 ; Console . WriteLine ( GetDiff ( arr , N ) ) ; } }