Largest number having both positive and negative values present in the array | 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
function largestNum ( arr ) { let set = new Set ( ) ; let res = 0 ; for ( let i = 0 ; i < arr . length ; i ++ ) { set . add ( arr [ i ] ) ; if ( set . has ( - 1 * arr [ i ] ) ) { res = Math . max ( res , Math . abs ( arr [ i ] ) ) ; } } return res ; } let arr = [ 3 , 2 , - 2 , 5 , - 3 ] ; document . write ( largestNum ( arr ) ) ;