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 resultant value of K ; Sort the array arr [ ] ; Initialize two variables to use two pointers technique ; Iterate until the value of l is less than r ; Find the value of the sum ; If the sum is 0 , then the resultant element is found ; If the sum is negative ; Otherwise , decrement r ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int largestNum ( vector < int > arr ) { int res = 0 ; sort ( arr . begin ( ) , arr . end ( ) ) ; int l = 0 , r = arr . size ( ) - 1 ; while ( l < r ) { int sum = arr [ l ] + arr [ r ] ; if ( sum == 0 ) { res = max ( res , max ( arr [ l ] , arr [ r ] ) ) ; return res ; } else if ( sum < 0 ) { l ++ ; } else { r -- ; } } return res ; } int main ( ) { vector < int > arr = { 3 , 2 , -2 , 5 , -3 } ; cout << ( largestNum ( arr ) ) ; }