Pair with given sum and maximum shortest distance from end | function to find maximum shortest distance ; stores the shortest distance of every element in original array . ; shortest distance from ends ; if duplicates are found , b [ x ] is replaced with minimum of the previous and current position 's  shortest distance ; similar elements ignore them cause we need distinct elements ; Driver code
def find_maximum ( a , n , k ) : NEW_LINE INDENT b = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT x = a [ i ] NEW_LINE d = min ( 1 + i , n - i ) NEW_LINE if x not in b . keys ( ) : NEW_LINE INDENT b [ x ] = d NEW_LINE DEDENT else : NEW_LINE INDENT b [ x ] = min ( d , b [ x ] ) NEW_LINE DEDENT DEDENT ans = 10 ** 9 NEW_LINE for i in range ( n ) : NEW_LINE INDENT x = a [ i ] NEW_LINE if ( x != ( k - x ) and ( k - x ) in b . keys ( ) ) : NEW_LINE INDENT ans = min ( max ( b [ x ] , b [ k - x ] ) , ans ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT a = [ 3 , 5 , 8 , 6 , 7 ] NEW_LINE K = 11 NEW_LINE n = len ( a ) NEW_LINE print ( find_maximum ( a , n , K ) ) NEW_LINE