Sponsored
Sponsored
This approach utilizes a HashSet to keep track of the numbers we have encountered. As we iterate through the list, we check both the presence of a number and its negative in the HashSet. We update the largest number that satisfies the condition.
Time Complexity: O(n), since we iterate through the array once.
Space Complexity: O(1), since the hash set array size is always constant and independent of input size.
1function largestEqualPositiveNegative(nums) {
2 const numSet = new Set();
3 let largest = -1;
4 for (const num of nums) {
5 if (numSet.has(-num)) {
6 largest = Math.max(largest, Math.abs(num));
7 }
8 numSet.add(num);
9 }
10 return largest;
11}
12
13const nums = [-1, 2, -3, 3];
14console.log(largestEqualPositiveNegative(nums)); // Output: 3
Uses a Set to enable fast look-up of numeric presence. For each number, the approach checks if its negative counterpart is in the Set, and updates the largest valid integer if both exist.
In this approach, we first sort the array so that we can efficiently find pairs of positive and negative numbers. Once sorted, we use two pointers: one starting from the beginning (for negative numbers) and one from the end (for positive numbers) to find the largest integer pair where both a positive and its negative exist.
Time Complexity: O(n log n) for the sorting operation.
Space Complexity: O(1) additional space beyond input storing.
public class Solution {
public int LargestEqualPositiveNegative(int[] nums) {
Array.Sort(nums);
int left = 0, right = nums.Length - 1, largest = -1;
while (left < right) {
int sum = nums[left] + nums[right];
if (sum == 0) {
largest = nums[right];
left++;
right--;
} else if (sum < 0) {
left++;
} else {
right--;
}
}
return largest;
}
public static void Main() {
Solution solution = new Solution();
int[] nums = {-1, 2, -3, 3};
Console.WriteLine(solution.LargestEqualPositiveNegative(nums)); // Output: 3
}
}
This method capitalizes on sorting and dual pointers to unify effective positive-negative pair search. Identifies largest k through numerical evaluations where pair sums are zero.