Find largest d in array such that a + b + c = d | A hashing based Java program to find largest d 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
import java . util . HashMap ; import java . lang . Math ; class Indexes { int i , j ; Indexes ( int i , int j ) { this . i = i ; this . j = j ; } int getI ( ) { return i ; } int getJ ( ) { return j ; } } class GFG { static int findFourElements ( int [ ] arr , int n ) { HashMap < Integer , Indexes > map = new HashMap < > ( ) ; for ( int i = 0 ; i < n - 1 ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { map . put ( arr [ i ] + arr [ j ] , new Indexes ( i , j ) ) ; } } int d = Integer . MIN_VALUE ; for ( int i = 0 ; i < n - 1 ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { int abs_diff = Math . abs ( arr [ i ] - arr [ j ] ) ; if ( map . containsKey ( abs_diff ) ) { Indexes 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 ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 5 , 7 , 12 } ; int n = arr . length ; int res = findFourElements ( arr , n ) ; if ( res == Integer . MIN_VALUE ) System . out . println ( " No ▁ Solution " ) ; else System . out . println ( res ) ; } }