Largest number having both positive and negative values present in the array | Java program for the above approach ; Function to find the largest number k such that both k and - k are present in the array ; Stores the array elements ; Initialize a variable res as 0 to store maximum element while traversing the array ; Iterate through array arr ; Add the current element into the set ; Check if the negative of this element is also present in the set or not ; Return the resultant element ; Drive Code
import java . io . * ; import java . util . * ; class GFG { public static int largestNum ( int [ ] arr ) { Set < Integer > set = new HashSet < > ( ) ; int res = 0 ; for ( int i = 0 ; i < arr . length ; i ++ ) { set . add ( arr [ i ] ) ; if ( set . contains ( - 1 * arr [ i ] ) ) { res = Math . max ( res , Math . abs ( arr [ i ] ) ) ; } } return res ; } public static void main ( String [ ] args ) { int [ ] arr = { 3 , 2 , - 2 , 5 , - 3 } ; System . out . println ( largestNum ( arr ) ) ; } }