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.
1#include <stdio.h>
2#include <stdlib.h>
3
4int largestEqualPositiveNegative(int* nums, int numsSize) {
5 int hash[2001] = {0}; // To accommodate numbers from -1000 to 1000
6 int largest = -1;
7 for (int i = 0; i < numsSize; i++) {
8 int num = nums[i];
9 hash[num + 1000] = 1; // Using offset 1000 to handle negative indices
10
11 if (num > 0 && hash[-num + 1000]) {
12 if (num > largest) {
13 largest = num;
14 }
15 } else if (num < 0 && hash[-num + 1000]) {
16 if (-num > largest) {
17 largest = -num;
18 }
19 }
20 }
21 return largest;
22}
23
24int main() {
25 int nums[] = {-1, 2, -3, 3};
26 int size = sizeof(nums) / sizeof(nums[0]);
27 printf("%d\n", largestEqualPositiveNegative(nums, size)); // Output: 3
28 return 0;
29}
The approach uses an integer array as a hash set to track numbers from -1000 to 1000. We check for each number if its opposite exists in the hash set. If it does, we see if it forms the largest valid integer.
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.
This approach sorts the array to facilitate efficient pair searching through two pointers. By manipulating two indices moving inwards, we detect equal absolute pairs and subsequently update the largest value.