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 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
import java . io . * ; import java . util . * ; public class GFG { public static int largestNum ( int [ ] arr ) { int res = 0 ; Arrays . sort ( arr ) ; int l = 0 , r = arr . length - 1 ; while ( l < r ) { int sum = arr [ l ] + arr [ r ] ; if ( sum == 0 ) { res = Math . max ( res , Math . max ( arr [ l ] , arr [ r ] ) ) ; return res ; } else if ( sum < 0 ) { l ++ ; } else { r -- ; } } return res ; } public static void main ( String [ ] args ) { int [ ] arr = { 3 , 2 , - 2 , 5 , - 3 } ; System . out . println ( largestNum ( arr ) ) ; } }