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.
#include <vector>
#include <algorithm>
int largestEqualPositiveNegative(std::vector<int>& nums) {
std::sort(nums.begin(), nums.end());
int left = 0, right = nums.size() - 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;
}
int main() {
std::vector<int> nums = {-1, 2, -3, 3};
std::cout << largestEqualPositiveNegative(nums) << std::endl; // Output: 3
return 0;
}
After sorting the array, the technique uses two pointers approach to evaluate possible pairs efficiently. Pairs with sum zero indicate valid positive-negative pairs, selecting the largest positive in such cases.