Menu Close

Program to find Largest Positive Integer That Exists With Its Negative

Here, we will see Program to find Largest Positive Integer That Exists With Its Negative with code and algorithm.

You are given an integer array nums that does not contain any zeros.

You have to find the largest positive integer k such that -k also exists in the array.

Return the positive integer k. If there is no such integer, return -1.

Example 1:

Input: nums = [-1,2,-3,3]
Output: 3
Explanation: 3 is the only valid k we can find in the array because 3 and -3 both are present in the array and largest within positive numbers in nums array.

Example 2:

Input: nums = [-1,10,6,7,-7,1]
Output: 7
Explanation: Both 1 and 7 have their corresponding negative values in the array. 7 has a larger value.

Example 3:

Input: nums = [-10,8,6,7,-2,-3]
Output: -1
Explanation: There is no a single valid k so we return -1. In the array there is no such element which has both positive and negative number of same like (-2 and 2).

Algorithm:

  • Create a map which will hold the nums array value
  • Iterate through nums array
    • If the value is negative then check If It’s a corresponding positive value is present or not in map.
    • If the value is positive then check If It’s a corresponding negative value is present or not in map.
    • If both positive and negative of same number is present then check whether this value is greater then value stored at max variable or not.

Program to find largest positive integer that exists with Its negative code in C++

Code 1:

#include <iostream>
#include <unordered_map>
#include <vector>
#include <limits.h>

using namespace std;

int findMaxK(vector<int>& nums) {
    unordered_map<int, bool> m;
    int max = INT_MIN;
    bool is_found = false;
        
    for(auto it : nums) {
        // Store value in map to check number is already present or not
        m[it] = true;
        if(it < 0) {
            it *= -1;
                
            if(m.find(it) != m.end()) {
                if(max < it) {
                    max = it;
                    is_found = true;
                }
            }
        } else {
            if(m.find(it * -1) != m.end()) {
                if(max < it) {
                    max = it;
                    is_found = true;
                }
            }
        }
    }
    if(is_found)
        return max;
    else
        return -1;
}

int main()
{
    vector<int> v = {-1,2,-3,3};
    
    cout<<findMaxK(v);

    return 0;
}

Output:

3

To check more leetcode problem’s solution. Pls click given below link:

https://www.techieindoor.com/category/leetcode/

Posted in C++, Easy

Leave a Reply

Your email address will not be published. Required fields are marked *