Skip to main content
Back to problems
Leetcode
Medium
Arrays
Hash Maps
Sets
Largest Positive Integer That Exists With Its Negative

Find the largest positive integer in an array whose negative also appears in the array.

Acceptance 0%
Problem Statement

Given an integer array, return the largest positive value kk such that both kk and k-k appear in the array.

If no such value exists, return 1-1.

The answer is based on the absolute value of matching positive/negative pairs, but only positive integers are considered as candidates.

Input Format

  • A single integer array nums.
  • Each element may be positive, negative, or zero.

Output Format

  • Return one integer: the largest positive integer k for which both k and -k exist in nums.
  • If no such integer exists, return -1.

Constraints

  • 1 <= nums.length.
  • Values may be repeated.
  • Zero does not count as a positive integer.
  • You may assume the array fits in memory and that a linear-time solution is expected.
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [-1, 2, -3, 3]

Output

3

Explanation

Both 3 and -3 appear, and 3 is the largest positive integer with its negative present.

Example 2

Input

nums = [-1, 10, 6, 7, -7, 1]

Output

7

Explanation

The pairs are 1 and -1, and 7 and -7. The largest valid positive integer is 7.

Show 1 more example

Example 3

Input

nums = [-10, 8, 6, 7, -2, -3]

Output

-1

Explanation

No positive integer has its negative also present.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.