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 st ; Check if the negative of this element is also present in the st or not ; Return the resultant element ; Drive Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int largestNum ( int arr [ ] , int n ) { set < int > st ; int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { st . insert ( arr [ i ] ) ; if ( st . find ( -1 * arr [ i ] ) != st . end ( ) ) { res = max ( res , abs ( arr [ i ] ) ) ; } } return res ; } int main ( ) { int arr [ ] = { 3 , 2 , -2 , 5 , -3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << largestNum ( arr , n ) ; }