Related Articles

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

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

Below is the implementation of the above approach:

## C++14

 `// C++ program for the above approach``#include``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;``}` `// 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;``    ``}` `    ``// 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` `    ``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;``}` `// 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

 ``
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``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``    ``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 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 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));``    ``}``}`

## Javascript

 ``

## 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;``    ``}`` ` `    ``// Drive Code``    ` `    ``static` `public` `void` `Main (){``        ` `        ``int``[] arr = { 3, 2, -2, 5, -3 };``        ``Console.WriteLine(``            ``largestNum(arr));``        ` `    ``}``}` `// This code is contributed by unknown2108`
Output:
`3`

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up