Largest number having both positive and negative values present in the array
Last Updated :
14 Apr, 2023
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++
#include <bits/stdc++.h>
using namespace std;
int largestNum(vector< int > &arr, int n) {
int maxK = -1;
for ( int i = 0; i < n; i++) {
for ( int j = i+1; j < n; j++) {
if (arr[i] == -arr[j] && abs (arr[i]) > maxK)
maxK = abs (arr[i]);
}
}
return maxK;
}
int main() {
vector< int > arr = {3, 2, -2, 5, -3};
int n = arr.size();
cout << (largestNum(arr, n));
return 0;
}
|
Java
import java.util.*;
public class GFG {
static int largestNum(ArrayList<Integer> arr, int n)
{
int maxK = - 1 ;
for ( int i = 0 ; i < n; i++) {
for ( int j = i + 1 ; j < n; j++) {
if (arr.get(i) == -arr.get(j)
&& Math.abs(arr.get(i)) > maxK)
maxK = Math.abs(arr.get(i));
}
}
return maxK;
}
public static void main(String[] args)
{
ArrayList<Integer> arr = new ArrayList<>(
Arrays.asList( 3 , 2 , - 2 , 5 , - 3 ));
int n = arr.size();
System.out.println(largestNum(arr, n));
}
}
|
Python3
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
{
static int LargestNum(List< int > arr, int n)
{
int maxK = -1;
for ( int i = 0; i < n; i++) {
for ( int j = i + 1; j < n; j++) {
if (arr[i] == -arr[j]
&& Math.Abs(arr[i]) > maxK)
maxK = Math.Abs(arr[i]);
}
}
return maxK;
}
static void Main( string [] args)
{
List< int > arr = new List< int >{ 3, 2, -2, 5, -3 };
int n = arr.Count;
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));
|
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++
#include<bits/stdc++.h>
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 == 0 ? -1 : res;
}
int main()
{
vector< int >arr = { 3, 2, -2, 5, -3 };
cout << (largestNum(arr));
}
|
Java
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 == 0 ? - 1 : res;
}
public static void main(String[] args)
{
int [] arr = { 3 , 2 , - 2 , 5 , - 3 };
System.out.println(
largestNum(arr));
}
}
|
Python3
def largestNum(arr):
res = 0
arr = sorted (arr)
l = 0
r = len (arr) - 1
while (l < r):
sum = arr[l] + arr[r]
if ( sum = = 0 ):
res = max (res, max (arr[l], arr[r]))
return res
elif ( sum < 0 ):
l + = 1
else :
r - = 1
if res = = 0 :
return - 1
return res
if __name__ = = '__main__' :
arr = [ 3 , 2 , - 2 , 5 , - 3 ]
print (largestNum(arr))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static int largestNum(List< int >arr)
{
int res = 0;
arr.Sort();
int l = 0, r = arr.Count - 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 == 0 ? -1 : res;
}
public static void Main()
{
List< int >arr = new List< int >(){ 3, 2, -2, 5, -3 };
Console.Write(largestNum(arr));
}
}
|
Javascript
<script>
function largestNum(arr) {
let res = 0;
arr.sort((a, b) => a - b);
let l = 0, r = arr.length - 1;
while (l < r) {
let 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 == 0 ? -1 : res;
}
let arr = [3, 2, -2, 5, -3];
document.write((largestNum(arr)));
</script>
|
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++
#include<bits/stdc++.h>
using namespace std;
int largestNum( int arr[] , int n)
{
unordered_set< int > st;
int res = 0;
for ( int i = 0; i < n; i++)
{
st.insert(arr[i]);
if (st.find(-1 * arr[i]) != st.end())
{
res = max(res, abs (arr[i]));
}
}
return res == 0 ? -1 : res;
}
int main()
{
int arr[] = { 3, 2, -2, 5, -3 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << largestNum(arr, n);
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
public static int largestNum( int [] arr)
{
Set<Integer> set = new HashSet<>();
int res = 0 ;
for ( int i = 0 ;
i < arr.length; i++) {
set.add(arr[i]);
if (set.contains(- 1 * arr[i])) {
res = Math.max(
res, Math.abs(arr[i]));
}
}
return res == 0 ? - 1 : res;
}
public static void
main(String[] args)
{
int [] arr = { 3 , 2 , - 2 , 5 , - 3 };
System.out.println(
largestNum(arr));
}
}
|
Python3
def largestNum(arr, n):
st = set ([])
res = 0
for i in range (n):
st.add(arr[i])
if ( - 1 * arr[i]) in st:
res = max (res, abs (arr[i]))
if res = = 0 :
return - 1
return res
arr = [ 3 , 2 , - 2 , 5 , - 3 ]
n = len (arr)
print (largestNum(arr, n))
|
C#
using System;
using System.Collections.Generic;
public class GFG{
public static int largestNum( int [] arr)
{
HashSet< int > set = new HashSet< int >();
int res = 0;
for ( int i = 0;
i < arr.Length; i++) {
set .Add(arr[i]);
if ( set .Contains(-1 * arr[i])) {
res = Math.Max(
res, Math.Abs(arr[i]));
}
}
return res == 0 ? -1 : res;
}
static public void Main (){
int [] arr = { 3, 2, -2, 5, -3 };
Console.WriteLine(
largestNum(arr));
}
}
|
Javascript
<script>
function largestNum(arr)
{
let set = new Set();
let res = 0;
for (let i = 0;
i < arr.length; i++) {
set.add(arr[i]);
if (set.has(-1 * arr[i])) {
res = Math.max(
res, Math.abs(arr[i]));
}
}
return res == 0 ? -1 : res;
}
let arr=[3, 2, -2, 5, -3 ];
document.write(largestNum(arr));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...