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++ // 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));
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>
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>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Find pairs of Positive and Negative values present in given array
Given an array of distinct integers, print all the pairs having both positive and negative values of a number that exists in the array. The pairs can be printed in any order. Examples: Input: arr[] = {1, -3, 2, 3, 6, -1}Output: -1 1 -3 3 Input: arr[] = {4, 8, 9, -4, 1, -1, -8, -9}Output: -4 4 -8 8 -
14 min read
Find ratio of zeroes, positive numbers and negative numbers in the Array
Given an array a of integers of size N integers, the task is to find the ratio of positive numbers, negative numbers and zeros in the array up to four decimal places. Examples: Input: a[] = {2, -1, 5, 6, 0, -3} Output: 0.5000 0.3333 0.1667 There are 3 positive, 2 negative, and 1 zero. Their ratio wo
7 min read
Largest number in an array that is not a perfect cube
Given an array of n integers. The task is to find the largest number which is not a perfect cube. Print -1 if there is no number that is a perfect cube. Examples: Input: arr[] = {16, 8, 25, 2, 3, 10} Output: 25 25 is the largest number that is not a perfect cube. Input: arr[] = {36, 64, 10, 16, 29,
8 min read
Largest number in the Array having frequency same as value
Given an array arr containing N integers, the task is to find the largest number in the array whose frequency is equal to its value. If no such number exists, then print -1.Examples: Input: arr = [3, 2, 5, 2, 4, 5] Output: 2 Explanation: In this given array frequency of 2 is 2, whereas the frequency
8 min read
Find the maximum among the count of positive or negative integers in the array
Given a sorted array arr[] consisting of N integers, the task is to find the maximum among the count of positive or negative integers in the array arr[]. Examples: Input: arr[] = {-9, -7, -4, 1, 5, 8, 9}Output: 4Explanation:The count of positive numbers is 4 and the count of negative numbers is 3. S
9 min read
Only integer with positive value in positive negative value in array
Given an array of N integers. In the given, for each positive element 'x' there exist a negative value '-x', except one integer whose negative value is not present. That integer may occur multiple number of time. The task is find that integer. Examples: Input : arr[] = { 1, 8, -6, -1, 6, 8, 8 } Outp
8 min read
Print all the pairs that contains the positive and negative values of an element
Given an array of distinct integers, print all the pairs having a positive value and negative value of a number that exists in the array. Note: Order of the pairs doesn't matter. Examples: Input: arr[] = { 1, -3, 2, 3, 6, -1 }Output: -1 1 -3 3Input: arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 }Output: -1 1
13 min read
Rearrange Array in negative numbers, zero and then positive numbers order
Given an arr[ ] of size N, containing positive, negative integers and one zero. The task is to rearrange the array in such a way that all negative numbers are on the left of 0 and all positive numbers are on the right. Note: It is not mandatory to maintain the order of the numbers. If there are mult
6 min read
Rearrange positive and negative numbers using inbuilt sort function
Given an array of positive and negative numbers, arrange them such that all negative integers appear before all the positive integers in the array without using any additional data structure like a hash table, arrays, etc. The order of appearance should be maintained. Examples: Input : arr[] = [12,
15 min read
Rearrange positive and negative numbers with constant extra space
Given an array arr[] of integers, the task is to arrange them such that all negative integers appear before all the positive integers in the array without using any additional data structure like a hash table, arrays, etc. The order of appearance should be maintained. Examples: Input: arr[] = [12, 1
15+ min read