Pair with given sum and maximum shortest distance from end | JavaScript code to find maximum shortest distance from endpoints ; Store counts of all elements . ; 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
function makePermutation ( a , n ) { let count = new Map ( ) ; for ( let i = 0 ; i < n ; i ++ ) { if ( count . has ( a [ i ] ) ) { count . set ( a [ i ] , count . get ( a [ i ] ) + 1 ) ; } else { count . set ( a [ i ] , 1 ) ; } } } function find_maximum ( a , n , k ) { let b = new Map ( ) ; for ( let i = 0 ; i < n ; i ++ ) { let x = a [ i ] ; let d = Math . min ( 1 + i , n - i ) ; if ( ! b . has ( x ) ) b . set ( x , d ) ; else { b . set ( x , Math . min ( d , b . get ( x ) ) ) ; } } let ans = Number . MAX_VALUE ; for ( let i = 0 ; i < n ; i ++ ) { let x = a [ i ] ; if ( x != k - x && b . has ( k - x ) ) ans = Math . min ( Math . max ( b . get ( x ) , b . get ( k - x ) ) , ans ) ; } return ans ; } let a = [ 3 , 5 , 8 , 6 , 7 ] ; let K = 11 ; let n = a . length ; document . write ( find_maximum ( a , n , K ) ) ;