[LeetCode] Largest Positive Integer That Exists With Its Negative

2441. Largest Positive Integer That Exists With Its Negative

Given an integer array nums that does not contain any zeros, 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.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int findMaxK(vector<int>& nums) {
unordered_set<int> us(begin(nums),end(nums));
int res = -1;
for(int i = 0; i < nums.size(); i++) {
if(nums[i] > 0 and us.count(-nums[i])) res = max(res,nums[i]);
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/16/PS/LeetCode/largest-positive-integer-that-exists-with-its-negative/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.