Calculate absolute difference between minimum and maximum sum of pairs in an array | Python 3 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 sys NEW_LINE def GetDiff ( A , N ) : NEW_LINE INDENT SuffMaxArr = [ 0 for i in range ( N ) ] NEW_LINE SuffMaxArr [ N - 1 ] = A [ N - 1 ] NEW_LINE i = N - 2 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT SuffMaxArr [ i ] = max ( SuffMaxArr [ i + 1 ] , A [ i + 1 ] ) NEW_LINE i -= 1 NEW_LINE DEDENT MaximumSum = - sys . maxsize - 1 NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT if ( A [ i ] < SuffMaxArr [ i ] ) : NEW_LINE INDENT MaximumSum = max ( MaximumSum , A [ i ] + SuffMaxArr [ i ] ) NEW_LINE DEDENT DEDENT MinimumSum = sys . maxsize NEW_LINE SuffMinArr = [ 0 for i in range ( N ) ] NEW_LINE SuffMinArr [ N - 1 ] = sys . maxsize NEW_LINE i = N - 2 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT SuffMinArr [ i ] = min ( SuffMinArr [ i + 1 ] , A [ i + 1 ] ) NEW_LINE i -= 1 NEW_LINE DEDENT for i in range ( N - 1 ) : NEW_LINE INDENT if ( A [ i ] < SuffMinArr [ i ] ) : NEW_LINE INDENT MinimumSum = min ( MinimumSum , A [ i ] + SuffMinArr [ i ] ) NEW_LINE DEDENT DEDENT return abs ( MaximumSum - MinimumSum ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 4 , 1 , 3 , 7 , 5 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE print ( GetDiff ( arr , N ) ) NEW_LINE DEDENT