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`.

30:00

Largest Positive Integer That Exists With Its Negative
easy
Free written solution
Topics
Companies

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.

Example 1:
Input: {"nums":[-1,2,-3,3]}
Output: 3
Constraints:
  • 1≤nums.length≤10001 \leq \text{nums.length} \leq 1000

  • −1000≤nums[i]≤1000-1000 \leq \text{nums}[i] \leq 1000

  • nums[i]≠0\text{nums}[i] \neq 0

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[-1,2,-3,3]}

We want the largest k with both k and -k present. Sorting puts the most negative value at the left end and the largest value at the right end.

folded number line: positives above, |negatives| below

+−03-12-33

nums

-1
2
-3
3

nums[lo]

-

nums[hi]

-

s = sum

-

lo (most negative left)
hi (largest left)
the farther one is dropped
mirror pair
Variables
VariableValue
lo0
hi3
s-
DepthFunction Call
Stack empty
0/3