Largest number having both positive and negative values present in the array - GeeksforGeeks

28 Jul, 2021
Given an array arr[] consisting of N integers, the task is to find the largest number K (> 0) such that both the values K and -K are present in the given array arr[]. If no such number exists, then print -1.
Examples:
Input: arr[] = {3, 2, -2, 5, -3}Output: 3
Input: arr[] = {1, 2, 3, -4}Output: -1
Naive Approach: The simplest approach to solve the given problem is to iterate over the array and for each element, traverse the remaining array to check if its negative value exists in the array or not. After complete traversal of the array, print the maximum such number obtained.
Time Complexity: O(N2)Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized by using Sorting and Two Pointers. Follow the steps below to solve this problem:
Initialize a variable, say res as -1 that stores the maximum element obtained.
Sort the given array arr[].
Initialize two variables, say l and r as 0 and (N – 1), and perform the following steps:If the value of (arr[l] + arr[r]) is equal to 0, then return the absolute value of arr[l] and arr[r].Otherwise, if the value of (arr[l] + arr[r]) is less than 0, then increment the value of l by 1.Otherwise, decrement the value of r by 1.
If the value of (arr[l] + arr[r]) is equal to 0, then return the absolute value of arr[l] and arr[r].
Otherwise, if the value of (arr[l] + arr[r]) is less than 0, then increment the value of l by 1.
Otherwise, decrement the value of r by 1.
After completing the above steps, print the value of res as the result.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include<bits/stdc++.h>using namespace std; // Function to find the largest// number k such that both k and// -k are present in the arrayint largestNum(vector<int>arr){         // Stores the resultant value    // of K    int res = 0;     // Sort the array arr[]    sort(arr.begin(), arr.end());     // Initialize two variables to    // use two pointers technique    int l = 0, r = arr.size() - 1;     // Iterate until the value of    // l is less than r    while (l < r)    {                 // Find the value of the sum        int sum = arr[l] + arr[r];         // If the sum is 0, then the        // resultant element is found        if (sum == 0)        {            res = max(res, max(arr[l], arr[r]));            return res;        }         // If the sum is negative        else if (sum < 0)        {            l++;        }         // Otherwise, decrement r        else        {            r--;        }    }    return res;} // Driver Codeint main(){    vector<int>arr = { 3, 2, -2, 5, -3 };    cout << (largestNum(arr));} // This code is contributed by amreshkumar3
// Java program for the above approach import java.io.*;import java.util.*; public class GFG {     // Function to find the largest    // number k such that both k and    // -k are present in the array    public static int largestNum(int[] arr)    {        // Stores the resultant value        // of K        int res = 0;         // Sort the array arr[]        Arrays.sort(arr);         // Initialize two variables to        // use two pointers technique        int l = 0, r = arr.length - 1;         // Iterate until the value of        // l is less than r        while (l < r) {             // Find the value of the sum            int sum = arr[l] + arr[r];             // If the sum is 0, then the            // resultant element is found            if (sum == 0) {                res = Math.max(                    res, Math.max(                             arr[l], arr[r]));                 return res;            }             // If the sum is negative            else if (sum < 0) {                l++;            }             // Otherwise, decrement r            else {                r--;            }        }         return res;    }     // Driver Code    public static void main(String[] args)    {        int[] arr = { 3, 2, -2, 5, -3 };        System.out.println(            largestNum(arr));    }}
# Python3 program for the above approach # Function to find the largest# number k such that both k and# -k are present in the arraydef largestNum(arr):       # Stores the resultant value    # of K    res = 0     # Sort the array arr[]    arr = sorted(arr)     # Initialize two variables to    # use two pointers technique    l = 0    r = len(arr) - 1     # Iterate until the value of    # l is less than r    while (l < r):         # Find the value of the sum        sum = arr[l] + arr[r]         # If the sum is 0, then the        # resultant element is found        if (sum == 0):            res = max(res, max(arr[l], arr[r]))             return res         # If the sum is negative        elif (sum < 0):            l += 1         # Otherwise, decrement r        else:            r-=1     return res # Driver Codeif __name__ == '__main__':    arr =[3, 2, -2, 5, -3]    print(largestNum(arr))     # This code is contributed by mohit kumar 29.
// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find the largest// number k such that both k and// -k are present in the arraystatic int largestNum(List<int>arr){         // Stores the resultant value    // of K    int res = 0;     // Sort the array arr[]    arr.Sort();     // Initialize two variables to    // use two pointers technique    int l = 0, r = arr.Count - 1;     // Iterate until the value of    // l is less than r    while (l < r)    {                 // Find the value of the sum        int sum = arr[l] + arr[r];         // If the sum is 0, then the        // resultant element is found        if (sum == 0)        {            res = Math.Max(res, Math.Max(arr[l],                                         arr[r]));            return res;        }         // If the sum is negative        else if (sum < 0)        {            l++;        }         // Otherwise, decrement r        else        {            r--;        }    }    return res;} // Driver Codepublic static void Main(){    List<int>arr = new List<int>(){ 3, 2, -2, 5, -3 };    Console.Write(largestNum(arr));}} // This code is contributed by bgangwar59
<script>// Javascript program for the above approach  // Function to find the largest// number k such that both k and// -k are present in the arrayfunction largestNum(arr) {     // Stores the resultant value    // of K    let res = 0;     // Sort the array arr[]    arr.sort((a, b) => a - b);     // Initialize two variables to    // use two pointers technique    let l = 0, r = arr.length - 1;     // Iterate until the value of    // l is less than r    while (l < r) {         // Find the value of the sum        let sum = arr[l] + arr[r];         // If the sum is 0, then the        // resultant element is found        if (sum == 0) {            res = Math.max(res, Math.max(arr[l], arr[r]));            return res;        }         // If the sum is negative        else if (sum < 0) {            l++;        }         // Otherwise, decrement r        else {            r--;        }    }    return res;} // Driver Code let arr = [3, 2, -2, 5, -3];document.write((largestNum(arr)));  // This code is contributed by _saurabh_jaiswal</script>
3
 
Time Complexity: O(N*log N)Auxiliary Space: O(1)
Optimized Approach: The above approach can be further optimized by storing the elements into a Set. Follow the steps below to solve this problem:
Initialize a set S that stores the array elements.
Initialize a variable, say res as -1 to store the maximum element while traversing the array.
Iterate over the range [0, N – 1] using the variable i and perform the following steps:Add the current element to the set S.If the element is present, then update the value of res to the current element.
Add the current element to the set S.
If the element is present, then update the value of res to the current element.
After completing the above steps, print the value of res as the result.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include<bits/stdc++.h>using namespace std; // Function to find the largest// number k such that both k and// -k are present in the arrayint largestNum(int arr[] ,int n){         // Stores the array elements    set<int> st;     // Initialize a variable res as    // 0 to store maximum element    // while traversing the array    int res = 0;     // Iterate through array arr    for(int i = 0; i < n; i++)    {                 // Add the current element        // into the st        st.insert(arr[i]);         // Check if the negative of        // this element is also        // present in the st or not        if (st.find(-1 * arr[i]) != st.end())        {            res = max(res, abs(arr[i]));        }    }     // Return the resultant element    return res;} // Drive Codeint main(){    int arr[] = { 3, 2, -2, 5, -3 };    int n = sizeof(arr) / sizeof(arr[0]);         cout << largestNum(arr, n);} // This code is contributed by SURENDRA_GANGWAR
// Java program for the above approach import java.io.*;import java.util.*; class GFG {     // Function to find the largest    // number k such that both k and    // -k are present in the array    public static int largestNum(int[] arr)    {        // Stores the array elements        Set<Integer> set = new HashSet<>();         // Initialize a variable res as        // 0 to store maximum element        // while traversing the array        int res = 0;         // Iterate through array arr        for (int i = 0;             i < arr.length; i++) {             // Add the current element            // into the set            set.add(arr[i]);             // Check if the negative of            // this element is also            // present in the set or not            if (set.contains(-1 * arr[i])) {                 res = Math.max(                    res, Math.abs(arr[i]));            }        }         // Return the resultant element        return res;    }     // Drive Code    public static void        main(String[] args)    {         int[] arr = { 3, 2, -2, 5, -3 };        System.out.println(            largestNum(arr));    }}
# Python3 program for the above approach # Function to find the largest# number k such that both k and# -k are present in the arraydef largestNum(arr, n) :          # Stores the array elements    st = set([])      # Initialize a variable res as    # 0 to store maximum element    # while traversing the array    res = 0      # Iterate through array arr    for i in range(n):                  # Add the current element        # into the st        st.add(arr[i])          # Check if the negative of        # this element is also        # present in the st or not        if (-1 * arr[i]) in st:                     res = max(res, abs(arr[i]))      # Return the resultant element    return res arr = [ 3, 2, -2, 5, -3 ]n = len(arr)  print(largestNum(arr, n)) # This code is contributed by divyeshrabadiya07
// C# program for the above approachusing System;using System.Collections.Generic; public class GFG{         // Function to find the largest    // number k such that both k and    // -k are present in the array    public static int largestNum(int[] arr)    {        // Stores the array elements        HashSet<int> set = new HashSet<int>();          // Initialize a variable res as        // 0 to store maximum element        // while traversing the array        int res = 0;          // Iterate through array arr        for (int i = 0;             i < arr.Length; i++) {              // Add the current element            // into the set            set.Add(arr[i]);              // Check if the negative of            // this element is also            // present in the set or not            if (set.Contains(-1 * arr[i])) {                  res = Math.Max(                    res, Math.Abs(arr[i]));            }        }          // Return the resultant element        return res;    }      // Drive Code         static public void Main (){                 int[] arr = { 3, 2, -2, 5, -3 };        Console.WriteLine(            largestNum(arr));             }} // This code is contributed by unknown2108
<script> // JavaScript program for the above approach  // Function to find the largest    // number k such that both k and    // -k are present in the arrayfunction largestNum(arr){    // Stores the array elements        let set = new Set();          // Initialize a variable res as        // 0 to store maximum element        // while traversing the array        let res = 0;          // Iterate through array arr        for (let i = 0;             i < arr.length; i++) {              // Add the current element            // into the set            set.add(arr[i]);              // Check if the negative of            // this element is also            // present in the set or not            if (set.has(-1 * arr[i])) {                  res = Math.max(                    res, Math.abs(arr[i]));            }        }          // Return the resultant element        return res;} // Drive Codelet arr=[3, 2, -2, 5, -3 ];document.write(largestNum(arr));  // This code is contributed by patel2127 </script>
3
 
Time Complexity: O(N)Auxiliary Space: O(N)
mohit kumar 29
amreshkumar3
bgangwar59
_saurabh_jaiswal
SURENDRA_GANGWAR
patel2127
unknown2108
divyeshrabadiya07
HashSet
two-pointer-algorithm
Arrays
Hash
Mathematical
Searching
Sorting
two-pointer-algorithm
Arrays
Searching
Hash
Mathematical
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Internal Working of HashMap in Java
Count pairs with given sum
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
Hashing | Set 2 (Separate Chaining)