Skip to main content

2441. Largest Positive Integer That Exists With Its Negative

https://leetcode.com/problems/largest-positive-integer-that-exists-with-its-negative/

Level: Easy

C++

class Solution {
public:
int findMaxK(vector<int>& nums) {
// define a set for nums
unordered_set<int> s(nums.begin(), nums.end());
// define a max value
int max_val = -1;
// iterate over the nums
for (int num : nums) {
// check if the number is positive
if (num > 0) {
// check if the negative number exists
if (s.count(-num)) {
// update the max value
max_val = max(max_val, num);
}
}
}
return max_val;
}
};

Python

class Solution:
def findMaxK(self, nums: List[int]) -> int:
largest = -1
s = set(nums)

for x in nums:
if x > 0:
if -x in s and x > largest:
largest = x
return largest

Analysis

  • Time: O(N)O(N)
  • Space: O(N)O(N)