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.
1def largest_equal_positive_negative(nums):
2 num_set = set()
3 largest = -1
4 for num in nums:
5 if -num in num_set:
6 largest = max(largest, abs(num))
7 num_set.add(num)
8 return largest
9
10nums = [-1, 2, -3, 3]
11print(largest_equal_positive_negative(nums)) # Output: 3
Uses a set to track numbers. For each number, checks if its negative is in the set, updating the largest absolute value if a pair is found.
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.