Largest Positive Integer That Exists With Its Negative

easy two pointers sorting array

Problem

Given an integer array nums that contains no zeros, find the largest positive integer k such that -k also appears in the array. Return that k, or -1 if no such integer exists.

Inputnums = [-1, 10, 6, 7, -7, 1]
Output7
Both 1 and 7 have their negatives present; 7 is the larger valid k.
Inputnums = [-10, 8, 6, 7, -2, -3]
Output-1
No value has its negation also in the array, so the answer is -1.

def find_max_k(nums):
    nums.sort()
    lo, hi = 0, len(nums) - 1
    while lo < hi:
        s = nums[lo] + nums[hi]
        if s == 0:
            return nums[hi]
        elif s < 0:
            lo += 1
        else:
            hi -= 1
    return -1
function findMaxK(nums) {
  nums.sort((a, b) => a - b);
  let lo = 0, hi = nums.length - 1;
  while (lo < hi) {
    const s = nums[lo] + nums[hi];
    if (s === 0) {
      return nums[hi];
    } else if (s < 0) {
      lo++;
    } else {
      hi--;
    }
  }
  return -1;
}
int findMaxK(int[] nums) {
    Arrays.sort(nums);
    int lo = 0, hi = nums.length - 1;
    while (lo < hi) {
        int s = nums[lo] + nums[hi];
        if (s == 0) {
            return nums[hi];
        } else if (s < 0) {
            lo++;
        } else {
            hi--;
        }
    }
    return -1;
}
int findMaxK(vector<int>& nums) {
    sort(nums.begin(), nums.end());
    int lo = 0, hi = nums.size() - 1;
    while (lo < hi) {
        int s = nums[lo] + nums[hi];
        if (s == 0) {
            return nums[hi];
        } else if (s < 0) {
            lo++;
        } else {
            hi--;
        }
    }
    return -1;
}
Time: O(n log n) Space: O(1)