Skip to main content
Back to problems
#2441
Easy Algorithms

Largest positive integer that exists with its negative

Array Hash Table Two Pointers Sorting
74.5% acceptance
Feb 25, 2026
1060
25
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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn find_max_k(nums: Vec<i32>) -> i32 {
    use std::collections::HashSet;
    let set: HashSet<i32> = nums.iter().cloned().collect();
    let mut ans = -1;
    for &v in &nums {
      if v > 0 && set.contains(&-v) {
        ans = ans.max(v);
      }
    }
    ans
  }
}