Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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.

C++




// C++ code for the 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 array
int largestNum(vector<int> &arr, int n) {
      // to store maximum k
    int maxK = -1;
   
      // loop through all elements and find it's negative
      // in array after it's index
    for(int i = 0; i < n; i++) {
        for(int j = i+1; j < n; j++) {
              // if found and is greater than previous
              // maxK then update maxK with it
            if(arr[i] == -arr[j] && abs(arr[i]) > maxK)
                maxK = abs(arr[i]);
        }
    }
   
    return maxK;
}
 
// Driver Code
int main() {
      // Input array
    vector<int> arr = {3, 2, -2, 5, -3};
      int n = arr.size();
   
      // Function Call
    cout << (largestNum(arr, n));
    return 0;
}


Java




// Java code for the approach
 
import java.util.*;
 
public class GFG {
    // Function to find the largest
    // number k such that both k and
    // -k are present in the array
    static int largestNum(ArrayList<Integer> arr, int n)
    {
        // to store maximum k
        int maxK = -1;
 
        // loop through all elements and find it's negative
        // in array after it's index
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                // if found and is greater than previous
                // maxK then update maxK with it
                if (arr.get(i) == -arr.get(j)
                    && Math.abs(arr.get(i)) > maxK)
                    maxK = Math.abs(arr.get(i));
            }
        }
 
        return maxK;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Input array
        ArrayList<Integer> arr = new ArrayList<>(
            Arrays.asList(3, 2, -2, 5, -3));
        int n = arr.size();
 
        // Function Call
        System.out.println(largestNum(arr, n));
    }
}


Python3




# Python3 program for the above approach
 
# Function to find the largest
# number k such that both k and
# -k are present in the array
def largestNum(arr):
  n=len(arr)
  maxk=-1
  for i in range(n):
     for j in range(i+1,n):
       if arr[i]==-arr[j] and abs(arr[i])>abs(maxk):
           maxk=abs(arr[i])
  return maxk
   
arr =[3, 2, -2, 5, -3]
print(largestNum(arr))


C#




using System;
using System.Collections.Generic;
 
class Program
{
 
  // Function to find the largest
  // number k such that both k and
  // -k are present in the array
  static int LargestNum(List<int> arr, int n)
  {
 
    // to store maximum k
    int maxK = -1;
 
    // loop through all elements and find it's negative
    // in array after it's index
    for (int i = 0; i < n; i++) {
      for (int j = i + 1; j < n; j++) {
        // if found and is greater than previous
        // maxK then update maxK with it
        if (arr[i] == -arr[j]
            && Math.Abs(arr[i]) > maxK)
          maxK = Math.Abs(arr[i]);
      }
    }
 
    return maxK;
  }
 
  static void Main(string[] args)
  {
     
    // Input array
    List<int> arr = new List<int>{ 3, 2, -2, 5, -3 };
    int n = arr.Count;
 
    // Function Call
    Console.WriteLine(LargestNum(arr, n));
  }
}


Javascript




function largestNum(arr) {
    let maxK = -1;
    for (let i = 0; i < arr.length; i++) {
        for (let j = i + 1; j < arr.length; j++) {
            if (arr[i] === -arr[j] && Math.abs(arr[i]) > maxK) {
                maxK = Math.abs(arr[i]);
            }
        }
    }
    return maxK;
}
 
const arr = [3, 2, -2, 5, -3];
console.log(largestNum(arr));


Output

3

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.
  • After completing the above steps, print the value of res as the result.

Below is the implementation of the above approach:

C++




// 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 array
int 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 == 0 ? -1 : res;
}
 
// Driver Code
int main()
{
    vector<int>arr = { 3, 2, -2, 5, -3 };
    cout << (largestNum(arr));
}
 
// This code is contributed by amreshkumar3


Java




// 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 == 0 ? -1 : res;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int[] arr = { 3, 2, -2, 5, -3 };
        System.out.println(
            largestNum(arr));
    }
}


Python3




# Python3 program for the above approach
 
# Function to find the largest
# number k such that both k and
# -k are present in the array
def 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
     
    if res == 0:
      return -1
     
    return res
 
# Driver Code
if __name__ == '__main__':
    arr =[3, 2, -2, 5, -3]
    print(largestNum(arr))
 
    # This code is contributed by mohit kumar 29.


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find the largest
// number k such that both k and
// -k are present in the array
static 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 == 0 ? -1 : res;
}
 
// Driver Code
public static void Main()
{
    List<int>arr = new List<int>(){ 3, 2, -2, 5, -3 };
    Console.Write(largestNum(arr));
}
}
 
// This code is contributed by bgangwar59


Javascript




<script>
// Javascript program for the above approach
 
 
// Function to find the largest
// number k such that both k and
// -k are present in the array
function 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 == 0 ? -1 : res;
}
 
// Driver Code
 
let arr = [3, 2, -2, 5, -3];
document.write((largestNum(arr)));
 
 
// This code is contributed by _saurabh_jaiswal
</script>


Output

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.
  • After completing the above steps, print the value of res as the result.

Below is the implementation of the above approach:

C++




// 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 array
int largestNum(int arr[] ,int n)
{
     
    // Stores the array elements
    unordered_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 == 0 ? -1 : res;
}
 
// Drive Code
int 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




// 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 == 0 ? -1 : res;
    }
 
    // Drive Code
    public static void
        main(String[] args)
    {
 
        int[] arr = { 3, 2, -2, 5, -3 };
        System.out.println(
            largestNum(arr));
    }
}


Python3




# Python3 program for the above approach
 
# Function to find the largest
# number k such that both k and
# -k are present in the array
 
 
def 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]))
 
    if res == 0:
        return -1
    # 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#




// C# program for the above approach
using 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 == 0 ? -1 : res;
    }
  
    // Drive Code
     
    static public void Main (){
         
        int[] arr = { 3, 2, -2, 5, -3 };
        Console.WriteLine(
            largestNum(arr));
         
    }
}
 
// This code is contributed by unknown2108


Javascript




<script>
 
// JavaScript program for the above approach
 
 // Function to find the largest
    // number k such that both k and
    // -k are present in the array
function 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 == 0 ? -1 : res;
}
 
// Drive Code
let arr=[3, 2, -2, 5, -3 ];
document.write(largestNum(arr));
 
 
// This code is contributed by patel2127
 
</script>


Output

3

Time Complexity: O(N)
Auxiliary Space: O(N)



Last Updated : 14 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads