Find largest d in array such that a + b + c = d | To store and retrieve indices pair i & j ; The function finds four elements with given sum X ; Store sums ( a + b ) of all pairs ( a , b ) in a hash table ; Traverse through all pairs and find ( d - c ) is present in hash table ; If d - c is present in hash table , ; Making sure that all elements are distinct array elements and an element is not considered more than once . ; Driver code
class Indexes { constructor ( i , j ) { this . i = i ; this . j = j ; } getI ( ) { return this . i ; } getJ ( ) { return this . j ; } } function findFourElements ( arr , n ) { let map = new Map ( ) ; for ( let i = 0 ; i < n - 1 ; i ++ ) { for ( let j = i + 1 ; j < n ; j ++ ) { map . set ( arr [ i ] + arr [ j ] , new Indexes ( i , j ) ) ; } } let d = Number . MIN_VALUE ; for ( let i = 0 ; i < n - 1 ; i ++ ) { for ( let j = i + 1 ; j < n ; j ++ ) { let abs_diff = Math . abs ( arr [ i ] - arr [ j ] ) ; if ( map . has ( abs_diff ) ) { let indexes = map . get ( abs_diff ) ; if ( indexes . getI ( ) != i && indexes . getI ( ) != j && indexes . getJ ( ) != i && indexes . getJ ( ) != j ) { d = Math . max ( d , Math . max ( arr [ i ] , arr [ j ] ) ) ; } } } } return d ; } let arr = [ 2 , 3 , 5 , 7 , 12 ] ; let n = arr . length ; let res = findFourElements ( arr , n ) ; if ( res == Number . MIN_VALUE ) document . write ( " " ) ; else document . write ( res ) ;