Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Largest value of K such that both K and -K exist in Array in given index range [L, R]

  • Last Updated : 30 Nov, 2021

Given an array, arr[] of N integers and 2 integers L and R, the task is to return the largest integer K greater than 0 and L<=K<=R, such that both values K and -K exist in array arr[]. If there is no such integer, then return 0

Examples:

Input: N = 5, arr[] = {3, 2, -2, 5, -3},  L = 2, R = 3
Output: 3
Explanation: The largest value of K in the range [2, 3] such that both K and -K exist in the array is 3 as 3 is present at arr[0] and -3 is present at arr[4].

Input: N = 4, arr[] = {1, 2, 3, -4},  L = 1, R = 4
Output: 0

 

Approach: The idea is to traverse the array and add the element into the Set and simultaneously check for the negative of it i.e, arr[i]*-1 into the Set. If it is found then push it into the vector possible[]. Follow the steps below to solve the problem:

  • Initialize an unordered_set<int> s[] to store the elements.
  • Initialize a vector possible[] to store the possible answers.
  • Iterate over the range [0, N) using the variable i and perform the following steps:
  • Initialize a variable ans as 0 to store the answer.
  • Iterate over the range [0, size) where size is the size of the vector possible[], using the variable i and perform the following steps:
    • If possible[i] is greater than equal to L and less than equal to R, then update the value of ans as the max of ans or possible[i].
  • After performing the above steps, print the value of ans as the answer.

Below is the implementation of the above approach.

C++14




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum value of K
int findMax(int N, int arr[], int L, int R)
{
 
    // Using a set to store the elements
    unordered_set<int> s;
 
    // Vector to store the possible answers
    vector<int> possible;
 
    // Store the answer
    int ans = 0;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // If set has it's negation,
        // check if it is max
        if (s.find(arr[i] * -1) != s.end())
            possible.push_back(abs(arr[i]));
        else
            s.insert(arr[i]);
    }
 
    // Find the maximum possible answer
    for (int i = 0; i < possible.size(); i++) {
        if (possible[i] >= L and possible[i] <= R)
            ans = max(ans, possible[i]);
    }
 
    return ans;
}
 
// Driver Code
int main()
{
 
    int arr[] = { 3, 2, -2, 5, -3 },
        N = 5, L = 2, R = 3;
 
    int max = findMax(N, arr, L, R);
 
    // Display the output
    cout << max << endl;
 
    return 0;
}

Java




// Java program for the above approach
import java.util.*;
 
public class GFG
{
   
// Function to find the maximum value of K
static int findMax(int N, int []arr, int L, int R)
{
 
    // Using a set to store the elements
    HashSet<Integer> s = new HashSet<Integer>();
   
    // ArrayList to store the possible answers
    ArrayList<Integer> possible
            = new ArrayList<Integer>();
 
    // Store the answer
    int ans = 0;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // If set has it's negation,
        // check if it is max
        if (s.contains(arr[i] * -1))
            possible.add(Math.abs(arr[i]));
        else
            s.add(arr[i]);
    }
 
    // Find the maximum possible answer
    for (int i = 0; i < possible.size(); i++) {
        if (possible.get(i) >= L && possible.get(i) <= R) {
            ans = Math.max(ans, possible.get(i));
        }
    }
 
    return ans;
}
 
// Driver Code
public static void main(String args[])
{
 
    int []arr = { 3, 2, -2, 5, -3 };
    int N = 5, L = 2, R = 3;
 
    int max = findMax(N, arr, L, R);
 
    // Display the output
    System.out.println(max);
 
}
}
 
// This code is contributed by Samim Hossain Mondal.

Python3




# Python3 program for the above approach
 
# Function to find the maximum value of K
def findMax(N, arr, L, R) :
 
    # Using a set to store the elements
    s = set();
 
    # Vector to store the possible answers
    possible = [];
 
    # Store the answer
    ans = 0;
 
    # Traverse the array
    for i in range(N) :
 
        # If set has it's negation,
        # check if it is max
        if arr[i] * -1 in s  :
            possible.append(abs(arr[i]));
        else :
            s.add(arr[i]);
 
    # Find the maximum possible answer
    for i in range(len(possible)) :
        if (possible[i] >= L and possible[i] <= R) :
            ans = max(ans, possible[i]);
 
    return ans;
 
# Driver Code
if __name__ ==  "__main__" :
 
    arr = [ 3, 2, -2, 5, -3 ];
    N = 5; L = 2; R = 3;
 
    Max = findMax(N, arr, L, R);
 
    # Display the output
    print(Max);
 
    # This code is contributed by Ankthon

C#




// Java program for the above approach
using System;
using System.Collections;
using System.Collections.Generic;
 
public class GFG
{
// Function to find the maximum value of K
static int findMax(int N, int []arr, int L, int R)
{
 
    // Using a set to store the elements
    HashSet<int> s = new HashSet<int>();
   
    // ArrayList to store the possible answers
    ArrayList possible = new ArrayList();
 
    // Store the answer
    int ans = 0;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // If set has it's negation,
        // check if it is max
        if (s.Contains(arr[i] * -1))
            possible.Add(Math.Abs(arr[i]));
        else
            s.Add(arr[i]);
    }
 
    // Find the maximum possible answer
    for (int i = 0; i < possible.Count; i++) {
        if ((int)possible[i] >= L && (int)possible[i] <= R) {
            ans = Math.Max(ans, (int)possible[i]);
        }
    }
 
    return ans;
}
 
// Driver Code
public static void Main()
{
 
    int []arr = { 3, 2, -2, 5, -3 };
    int N = 5, L = 2, R = 3;
 
    int max = findMax(N, arr, L, R);
 
    // Display the output
    Console.Write(max);;
 
}
}
 
// This code is contributed by Samim Hossain Mondal.

Javascript




<script>
 
        // JavaScript Program to implement
        // the above approach
 
        // Function to find the maximum value of K
        function findMax(N, arr, L, R) {
 
            // Using a set to store the elements
            let s = new Set();
 
            // Vector to store the possible answers
            let possible = [];
 
            // Store the answer
            let ans = 0;
 
            // Traverse the array
            for (let i = 0; i < N; i++) {
 
                // If set has it's negation,
                // check if it is max
                if (s.has(arr[i] * -1))
                    possible.push(Math.abs(arr[i]));
                else
                    s.add(arr[i]);
            }
 
            // Find the maximum possible answer
            for (let i = 0; i < possible.length; i++) {
                if (possible[i] >= L && possible[i] <= R)
                    ans = Math.max(ans, possible[i]);
            }
 
            return ans;
        }
 
        // Driver Code
        let arr = [3, 2, -2, 5, -3];
        let N = 5, L = 2, R = 3;
 
        let max = findMax(N, arr, L, R);
 
        // Display the output
        document.write(max + '<br');
 
    // This code is contributed by Potta Lokesh
    </script>
Output
3

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


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!