Skip to content

2441. Largest Positive Integer That Exists With Its Negative 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  int findMaxK(vector<int>& nums) {
    int ans = -1;
    unordered_set<int> seen;

    for (const int num : nums)
      if (seen.contains(-num))
        ans = max(ans, abs(num));
      else
        seen.insert(num);

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
public class Solution {
  public int findMaxK(int[] nums) {
    int ans = -1;
    Set<Integer> seen = new HashSet<>();

    for (final int num : nums)
      if (seen.contains(-num))
        ans = Math.max(ans, Math.abs(num));
      else
        seen.add(num);

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def findMaxK(self, nums: list[int]) -> int:
    ans = -1
    seen = set()

    for num in nums:
      if -num in seen:
        ans = max(ans, abs(num))
      else:
        seen.add(num)

    return ans