Largest number having both positive and negative values present in the array | C # 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
using System ; using System . Collections . Generic ; public class GFG { public static int largestNum ( int [ ] arr ) { HashSet < int > set = new HashSet < int > ( ) ; 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 ; } static public void Main ( ) { int [ ] arr = { 3 , 2 , - 2 , 5 , - 3 } ; Console . WriteLine ( largestNum ( arr ) ) ; } }