question_slug
stringlengths
3
77
title
stringlengths
1
183
slug
stringlengths
12
45
summary
stringlengths
1
160
author
stringlengths
2
30
certification
stringclasses
2 values
created_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
updated_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
hit_count
int64
0
10.6M
has_video
bool
2 classes
content
stringlengths
4
576k
upvotes
int64
0
11.5k
downvotes
int64
0
358
tags
stringlengths
2
193
comments
int64
0
2.56k
largest-positive-integer-that-exists-with-its-negative
💯Faster✅💯Lesser✅2 Methods🧠Detailed Approach🎯Two Pointer🔥Python🐍Java☕C++😎
fasterlesser2-methodsdetailed-approachtw-3p7a
\uD83D\uDE80 Hi, I\'m Mohammed Raziullah Ansari, and I\'m excited to share 2 ways to solve this question with detailed explanation of each approach:\n\n# \uD83C
Mohammed_Raziullah_Ansari
NORMAL
2024-05-02T01:01:54.847128+00:00
2024-05-02T19:02:49.215536+00:00
24,235
false
# \uD83D\uDE80 Hi, I\'m [Mohammed Raziullah Ansari](https://leetcode.com/Mohammed_Raziullah_Ansari/), and I\'m excited to share 2 ways to solve this question with detailed explanation of each approach:\n\n# \uD83C\uDFAFProblem Explaination: \nYou are given an array of integers. Your task is to find the largest positive integer in the array such that its negative counterpart also exists in the array. If such a pair exists, return the largest positive integer; otherwise, return -1.\n\n### \uD83D\uDCE5Input:\n\n- An array of integers `nums`.\n- Each integer `nums[i]` represents an element of the array.\n\n### \uD83D\uDCE4Output:\n\n- An integer representing the largest positive integer satisfying the given condition. If no such integer exists, return -1.\n\n# \uD83D\uDD0D Methods To Solve This Problem:\nI\'ll be covering two different methods to solve this problem:\n1. Sorting\n2. Two Pointers\n\n# 1\uFE0F\u20E3 Sorting: \n\n### Approach\uD83E\uDD13:\n- Sort the array in ascending order.\n- Iterate through the sorted array from the end.\n- Return the first positive integer and its negative counterpart.\n### Complexity\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83D\uDD2C:\n- \u23F0 Time complexity: O(n log n) due to sorting.\n- \uD83C\uDF0C Space Complexity: O(1)\n\n<!-- ### Algorithm\uD83E\uDD13:\n\n1. Initialize an empty list to store rectangles.\n2. Iterate through each cell in the grid:\n - If a cell contains `1` and hasn\'t been visited:\n - Initiate a DFS from that cell to explore the connected farmland.\n - During DFS, keep track of the boundaries (min/max row and column) of the current region.\n - Once DFS completes for a region, record the rectangle\'s coordinates.\n3. Implement the DFS function recursively or using a stack to traverse adjacent cells.\n4. Return the list of identified rectangles. -->\n\n<!-- # Complexity\n- \u23F1\uFE0F Time Complexity: `O(n)` where n is the number of pairs in the list.\n -->\n<!-- - \uD83D\uDE80 Space Complexity: `O(n)` for the HashSet. -->\n\n# Code\uD83D\uDC68\uD83C\uDFFB\u200D\uD83D\uDCBB:\n```Python []\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n nums.sort()\n n = len(nums)\n for i in range(n-1, -1, -1):\n if nums[i] > 0 and -nums[i] in nums:\n return nums[i]\n return -1 # If no such pair found\n```\n```Java []\nclass Solution {\n public int findMaxK(int[] nums) {\n Arrays.sort(nums);\n int n = nums.length;\n for (int i = n-1; i >= 0; i--) {\n if (nums[i] > 0 && Arrays.binarySearch(nums, -nums[i]) >= 0) {\n return nums[i];\n }\n }\n return -1; // If no such pair found\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int findMaxK(std::vector<int>& nums) {\n std::sort(nums.begin(), nums.end());\n int n = nums.size();\n for (int i = n-1; i >= 0; i--) {\n if (nums[i] > 0 && std::binary_search(nums.begin(), nums.end(), -nums[i])) {\n return nums[i];\n }\n }\n return -1; // If no such pair found\n }\n};\n```\n\n# 2\uFE0F\u20E3 Two Pointers:\n### Approach\uD83D\uDE0E:\n- Sort the array in ascending order.\n- Use two pointers, one starting from the beginning and one from the end.\n- Move the pointers towards each other until you find a positive integer with its negative counterpart.\n- Keep track of the largest positive integer found.\n### Complexity\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83D\uDD2C:\n- \u23F0 Time complexity: O(n log n) due to sorting.\n- \uD83C\uDF0C Space Complexity: O(1)\n\n<!-- \n### Algorithm\uD83D\uDE0E:\n\n1. Initialize a queue (`queue`) to perform BFS and a set (`visited`) to keep track of visited cells.\n2. Iterate through each cell `(i, j)` in the grid:\n - If `land[i][j]` is `1` and `(i, j)` is not visited:\n - Initialize `min_row`, `min_col`, `max_row`, `max_col` to the current cell `(i, j)`.\n - Enqueue `(i, j)` into the queue and mark it as visited.\n - While the queue is not empty:\n - Dequeue a cell `(cur_i, cur_j)` from the queue.\n - Explore its four neighboring cells `(nx, ny)` (up, down, left, right).\n - If `(nx, ny)` is within the grid bounds and `land[nx][ny]` is `1` and not visited:\n - Enqueue `(nx, ny)`.\n - Mark `(nx, ny)` as visited.\n - Update `min_row`, `min_col`, `max_row`, `max_col` based on `(nx, ny)`.\n - After BFS completes for the current region, record the rectangle `[min_row, min_col, max_row, max_col]`.\n3. Return the list of identified rectangles. -->\n\n<!-- # Complexity\n- \u23F1\uFE0F Time Complexity: `O(n)` where n is the number of pairs in the list.\n\n- \uD83D\uDE80 Space Complexity: `O(n)` for the two lists. -->\n\n# Code\uD83D\uDC69\uD83C\uDFFB\u200D\uD83D\uDCBB:\n```Python []\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n nums.sort()\n left, right = 0, len(nums) - 1\n max_k = float(\'-inf\')\n while left < right:\n if nums[left] + nums[right] == 0:\n max_k = max(max_k, nums[right])\n left += 1\n right -= 1\n elif nums[left] + nums[right] < 0:\n left += 1\n else:\n right -= 1\n return max_k if max_k != float(\'-inf\') else -1 # If no such pair found\n```\n```Java []\nclass Solution {\n public int findMaxK(int[] nums) {\n Arrays.sort(nums);\n int left = 0, right = nums.length - 1;\n int maxK = Integer.MIN_VALUE;\n while (left < right) {\n int sum = nums[left] + nums[right];\n if (sum == 0) {\n maxK = Math.max(maxK, nums[right]);\n left++;\n right--;\n } else if (sum < 0) {\n left++;\n } else {\n right--;\n }\n }\n return maxK != Integer.MIN_VALUE ? maxK : -1; // If no such pair found\n }\n}\n\n```\n```C++ []\nclass Solution {\npublic:\n int findMaxK(std::vector<int>& nums) {\n std::sort(nums.begin(), nums.end());\n int left = 0, right = nums.size() - 1;\n int maxK = std::numeric_limits<int>::min();\n while (left < right) {\n int sum = nums[left] + nums[right];\n if (sum == 0) {\n maxK = std::max(maxK, nums[right]);\n left++;\n right--;\n } else if (sum < 0) {\n left++;\n } else {\n right--;\n }\n }\n return maxK != std::numeric_limits<int>::min() ? maxK : -1; // If no such pair found\n }\n};\n```\n# \uD83D\uDCA1 I invite you to check out [my profile](https://leetcode.com/Mohammed_Raziullah_Ansari/) for detailed explanations and code for each method. Happy coding and learning! \uD83D\uDCDA
62
7
['Array', 'Hash Table', 'Two Pointers', 'Binary Search', 'Sorting', 'C++', 'Java', 'Python3']
32
largest-positive-integer-that-exists-with-its-negative
✅C++ | ✅2 pointers approach | ✅Easy Approach
c-2-pointers-approach-easy-approach-by-y-4p6u
Please upvote if you find this solution helpful :)\n\nclass Solution \n{\npublic:\n int findMaxK(vector<int>& nums) \n {\n sort(nums.begin(), nums.
Yash2arma
NORMAL
2022-10-16T04:01:18.889269+00:00
2022-10-16T09:08:49.219127+00:00
7,399
false
**Please upvote if you find this solution helpful :)**\n```\nclass Solution \n{\npublic:\n int findMaxK(vector<int>& nums) \n {\n sort(nums.begin(), nums.end());\n int low=0, high=nums.size()-1;\n \n while(low < high)\n {\n if((nums[low] + nums[high]) == 0)\n {\n return nums[high];\n }\n \n else if((nums[low] + nums[high]) < 0)\n low++;\n \n else high--;\n }\n return -1;\n }\n};\n```
62
1
['Two Pointers', 'C', 'C++']
11
largest-positive-integer-that-exists-with-its-negative
[Python3] simple O(n) beginner friendly!
python3-simple-on-beginner-friendly-by-m-t4f2
First, convert the nums into a set for quick access.\nSecond, go over the entire nums, for each element k, do:\n1. check if k is positive.\n2. check if -k exist
MeidaChen
NORMAL
2022-10-16T04:01:40.826841+00:00
2024-01-04T19:24:58.382170+00:00
3,155
false
First, convert the nums into a set for quick access.\nSecond, go over the entire nums, for each element k, do:\n1. check if k is positive.\n2. check if -k exist in nums using the set, which takes O(1).\n3. check if k is larger than the largest element we have seen so far. And if it is, update the largest element so far and the result.\n\n```\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n Set = set(nums) ### convert nums into a set\n maxSoFar = -inf\n res = -inf\n for n in nums:\n \t### check condition 1-3\n if n>0 and -n in Set and n>maxSoFar:\n maxSoFar = n\n res = n\n ### If there is no such integer (res==-inf which never got updated), return -1.\n return res if res!=-inf else -1\n```\n\n**Upvote** if you like this post.\n\n**Connect with me on [LinkedIn](https://www.linkedin.com/in/meida-chen-938a265b/)** if you\'d like to discuss other related topics\n\n\uD83C\uDF1F If you are interested in **Machine Learning** || **Deep Learning** || **Computer Vision** || **Computer Graphics** related projects and topics, check out my **[YouTube Channel](https://www.youtube.com/@meidachen8489)**! Subscribe for regular updates and be part of our growing community.
40
5
[]
11
largest-positive-integer-that-exists-with-its-negative
Array
array-by-votrubac-w1qy
C++\ncpp\nint findMaxK(vector<int>& nums) {\n int arr[2001] = {}, res = -1;\n for (int n : nums) {\n if (arr[-n + 1000])\n res = max(res
votrubac
NORMAL
2022-10-16T04:03:27.271827+00:00
2022-10-16T04:03:27.271866+00:00
2,374
false
**C++**\n```cpp\nint findMaxK(vector<int>& nums) {\n int arr[2001] = {}, res = -1;\n for (int n : nums) {\n if (arr[-n + 1000])\n res = max(res, abs(n));\n ++arr[n + 1000]; \n }\n return res;\n}\n```
37
0
[]
6
largest-positive-integer-that-exists-with-its-negative
👏Best Java Solution🎉 || ⏩Fastest🤯 ||✅Simple & Easy Well Explained Approach🔥💥
best-java-solution-fastest-simple-easy-w-v8h2
Intuition\nThe problem aims to find the maximum absolute value among pairs of numbers where one is the negative of the other, given an array of integers. It uti
Rutvik_Jasani
NORMAL
2024-05-02T03:17:06.610584+00:00
2024-05-03T04:17:08.930086+00:00
4,069
false
# Intuition\nThe problem aims to find the maximum absolute value among pairs of numbers where one is the negative of the other, given an array of integers. It utilizes HashSet for efficient lookup of negative counterparts.\n\n# I Think This Can Help You(For Proof Click on the Image)\n[![Screenshot 2024-02-24 232407.png](https://assets.leetcode.com/users/images/8e502460-a001-4013-beb4-cef8252da000_1714619726.0656989.png)](https://leetcode.com/problems/largest-positive-integer-that-exists-with-its-negative/submissions/1247032507/?envType=daily-question&envId=2024-05-02)\n\n# Approach\n1. **HashSet Initialization**:\n ```java\n HashSet<Integer> hs = new HashSet<>();\n ```\n This line initializes a HashSet named `hs` to store integer values. HashSet is used because it provides constant-time average complexity for basic operations like add and contains.\n\n2. **Iterating Through the Array**:\n ```java\n for (int num : nums) {\n // Loop body\n }\n ```\n This loop iterates over each element `num` in the input array `nums`.\n\n3. **Adding Elements to HashSet**:\n ```java\n hs.add(num);\n ```\n Inside the loop, each encountered number `num` is added to the HashSet `hs`.\n\n4. **Calculating Negative of the Number**:\n ```java\n int k = num * (-1);\n ```\n This line calculates the negative of the current number `num` and stores it in variable `k`.\n\n5. **Checking for Negative Counterpart**:\n ```java\n if (hs.contains(k)) {\n // Code block\n }\n ```\n It checks if the HashSet `hs` contains the negative counterpart `k` of the current number `num`. If it does, it means there\'s a pair with one number being the negative of the other.\n\n6. **Updating Maximum Absolute Value**:\n ```java\n ans = Math.max(ans, Math.abs(num));\n ```\n If a pair is found, it updates the `ans` variable with the maximum absolute value among the current number `num` and the current value of `ans`.\n\n7. **Returning the Maximum Absolute Value**:\n ```java\n return ans;\n ```\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```java\nclass Solution {\n public int findMaxK(int[] nums) {\n HashSet<Integer> hs = new HashSet<>();\n int ans = -1;\n for(int num : nums){\n hs.add(num);\n int k = num*(-1);\n if(hs.contains(k)){\n ans = Math.max(ans,Math.abs(num));\n }\n }\n return ans;\n }\n}\n```\n\n![_a0e33399-39b7-476a-994b-e8aaac97926c.jpeg](https://assets.leetcode.com/users/images/973cb0ff-dd7a-4454-8aab-7b5b89a74a2b_1714709826.2688804.jpeg)\n
29
0
['Array', 'Hash Table', 'Two Pointers', 'Sorting', 'Java']
4
largest-positive-integer-that-exists-with-its-negative
Python || 2 lines, T/S: 97%/ 77%
python-2-lines-ts-97-77-by-spaulding-96i1
\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n nums = set(nums)\n return max(({x for x in nums if -x in nums}), default=-1)\
Spaulding_
NORMAL
2022-10-16T17:29:44.337486+00:00
2024-06-15T19:14:51.761767+00:00
885
false
```\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n nums = set(nums)\n return max(({x for x in nums if -x in nums}), default=-1)\n```\n[https://leetcode.com/problems/largest-positive-integer-that-exists-with-its-negative/submissions/1246950981/](https://leetcode.com/problems/largest-positive-integer-that-exists-with-its-negative/submissions/1246950981/)\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(*N*), in which *N* ~ `len(set(nums))`.
25
0
['Python', 'Python3']
4
largest-positive-integer-that-exists-with-its-negative
✅Variation of TWO SUM Problem||Two approaches
variation-of-two-sum-problemtwo-approach-pzmw
First Approach\n#### This problem is similar to Two sum problem \n\nTwo Sum Problem :- finding two elements that make up a sum k\nThis problem :- the value of
dinesh55
NORMAL
2022-10-16T04:28:44.067070+00:00
2022-10-16T08:40:03.767962+00:00
1,976
false
### First Approach\n#### This problem is similar to Two sum problem \n\n`Two Sum Problem :- finding two elements that make up a sum k`\n`This problem :- the value of k is zero that is sum we need to find is 0 and then if there are multiple of them return the max`\n\nSo simply we need to find its additive inverse \n\n```c++\n#include<bits/stdc++.h>\nusing namespace std;\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n\t\t// keep track of maximum\n int maxi = INT_MIN;\n\t\t// set to remeber the other value \n unordered_set<int> s;\n for(auto i : nums){\n if(s.find(i * -1) == s.end()){\n\t\t\t\t// if not found insert\n s.insert(i);\n }else{\n\t\t\t\t// if found update maxi \n maxi = max(maxi, abs(i));\n }\n }\n\t\t// if not present return -1 else return maxi\n return maxi == INT_MIN ? -1 : maxi;\n }\n};\n// time complexiy O(n) \n// space complexity O(n)\n```\n### Second Approach \n\n* sort the numbers then using two pointers solve the problem\n\n```c++\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n\t\t// sort the numbers O(nlogn)\n sort(nums.begin(), nums.end());\n int l = 0, h = nums.size() - 1;\n while(l < h){\n int sum = nums[l] + nums[h];\n\t\t\t// if sum is zero we have found our answer\n if(sum == 0)\n return nums[h];\n\t\t\t// if sum is positive then we need to push right pointer to reduce the positiveness \n else if(sum > 0){\n h--;\n }else{\n l++;\n }\n }\n\t\t// If not found\n return -1;\n }\n};\n// Time complexity: O(nlogn)\n// Space complexity O(1)\n// IDK Why but this one is faster than the O(n) solution\n```\n##### Edit:- \n\n* The reason Why the first approach is little bit slower is because unordered_map does some internal hashing which also costs some time \n* But as the value of n keeps on increasing O(n) << O(nlogn) i.e time for computing Hash would be significantly lower than sorting\n\n[dvsip](https://leetcode.com/dvisp/) Thank you for pointing this out.
23
0
['Array', 'C', 'Sorting']
7
largest-positive-integer-that-exists-with-its-negative
2 methods||sort+2 pointer vs 1 pass seen Array||8ms Beats 97.34%
2-methodssort2-pointer-vs-1-pass-seen-ar-eocb
Intuition\n Describe your first thoughts on how to solve this problem. \n2 methods.\n1. Sorting nums + 2 pointer\n2. 1 pass using seen array (a unsigned char ar
anwendeng
NORMAL
2024-05-02T01:40:32.472173+00:00
2024-05-02T01:52:34.869422+00:00
5,685
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n2 methods.\n1. Sorting nums + 2 pointer\n2. 1 pass using seen array (a unsigned char array is enough)\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe 1st method needs sorting O(n log n) time which is a very standard method; then use 2-pointer to find the answer.\n\nThe 2nd method use a uint8_t array instead of the slow C++ unordered_map or unordered_set.\nThe bit manipulation trick is so: if negative x is seen set seen[-x]|=2, if positive x is seen set seen[x]|=1. seen[x]==3 $\\iff$ both x, -x are seen.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n\\log n)$$ vs $$O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$O(1)$ vs $$O(n)$$\n# C++ sort+ 2 pointer||11 ms Beats 94.04%\n```\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n int n=nums.size(), l=0, r=n-1;\n sort(nums.begin(), nums.end());\n while(l<r && nums[l]!=-nums[r]){\n if (-nums[l]>nums[r]) l++;\n else r--;\n\n }\n return (l<r) ?nums[r]:-1;\n \n }\n};\n```\n# Code using seen array||8ms Beats 97.34%\n```\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n uint8_t seen[1001]={0};\n int k=-1;\n for(int x:nums){\n if (x<0) {\n x=-x;\n seen[x]|=2;\n }\n else seen[x]|=1;\n if (seen[x]==3 && x>k) k=x;\n }\n return k;\n }\n};\n```
22
0
['Array', 'Two Pointers', 'Bit Manipulation', 'Sorting', 'C++']
6
largest-positive-integer-that-exists-with-its-negative
Hashing [C++/Java]
hashing-cjava-by-xxvvpp-40eu
Count positive whose negative is there in the array using hashing.\n\nTime - O(n)\nSpace - O(n)\n# C++\n int findMaxK(vector& a) {\n unordered_set st(
xxvvpp
NORMAL
2022-10-16T04:01:57.176722+00:00
2022-10-16T04:10:52.980083+00:00
2,738
false
Count positive whose `negative` is there in the array using `hashing`.\n\nTime - O(`n`)\nSpace - O(`n`)\n# C++\n int findMaxK(vector<int>& a) {\n unordered_set<int> st(begin(a),end(a));\n int res = -1;\n for(int p : a) \n if(p > 0 and st.count(-p)) res = max(res , p);\n return res;\n }\n\t\n# Java\n public int findMaxK(int[] nums) {\n HashSet<Integer> st = new HashSet<>();\n for (int i : nums) st.add(i);\n int res = -1;\n for (int p : nums)\n\t\t if (p > 0 && st.contains(-p)) res = Math.max(res, p);\n return res;\n }
22
1
['C', 'Java']
9
largest-positive-integer-that-exists-with-its-negative
C++ || 6 different approaches || clean code
c-6-different-approaches-clean-code-by-h-jjrk
The leetcode runtimes are not very consistent, but approach 3 seems to be the fastest.\n\n### Approach 1: brute force (127ms)\n\nThe problem is constraint enoug
heder
NORMAL
2022-10-16T18:43:25.252560+00:00
2024-05-02T19:15:28.592682+00:00
1,064
false
The leetcode runtimes are not very consistent, but approach 3 seems to be the fastest.\n\n### Approach 1: brute force (127ms)\n\nThe problem is constraint enough that we can just use brute force.\n\n```cpp\n static int findMaxK(const vector<int>& nums) {\n int ans = -1;\n for (int i : nums)\n for (int j : nums)\n if (i == -j) ans = max(ans, abs(i));\n\n return ans;\n }\n```\n\n**Complexity Analysis**\n * Time complexity: $$O(n^2)$$\n * Space complexity: $$O(1)$$\n\n### Approach 2: hash set, two passes (42ms)\n\nIn the first pass we keep track of all the negative numbers in a hash set and in the next pass we look at all to positive numbers.\n\n```cpp\n static int findMaxK(const vector<int>& nums) {\n unordered_set<int> neg;\n for (int num : nums) {\n if (num < 0) neg.insert(num);\n }\n int ans = -1;\n for (int num : nums) {\n if (num > ans && neg.count(-num)) ans = num;\n }\n return ans;\n }\n```\n\n**Complexity Analysis**\n * Time complexity: $$O(n)$$\n * Space complexity: $$O(n)$$\n\n### Approach 3: bitset, two passes (7ms)\n\nThe input range is limited enough that we can just use a ```bitset```.\n\n```cpp\n static int findMaxK(const vector<int>& nums) {\n bitset<1024> neg;\n for (int num : nums) {\n if (num < 0) neg[-num] = true;\n }\n int ans = -1;\n for (int num : nums) {\n if (num > ans && neg[num]) ans = num;\n }\n return ans;\n }\n```\n\n**Complexity Analysis**\n * Time complexity: $$O(n)$$\n * Space complexity: $$O(1)$$ albeit it\'s a big 1.\n\n### Approach 4: hash set, single pass (36ms)\n\nIf we keep track of both negative and positive numbers we can also solve the problem in a single pass.\n\n```cpp\n static int findMaxK(const vector<int>& nums) {\n int ans = 0;\n unordered_set<int> seen;\n for (int num : nums) {\n const int abs_num = abs(num);\n if (abs_num > ans && seen.count(-num)) ans = abs_num;\n seen.insert(num);\n }\n return ans ?: -1;\n }\n```\n\nThe complexity is the same as approach 2.\n\n### Approach 5: bitset, single pass (29ms)\n\nAgain, we can just use a ```bitset```.\n\n```cpp\n static int findMaxK(const vector<int>& nums) {\n int ans = 0;\n bitset<2048> seen;\n for (int num : nums) {\n const int abs_num = abs(num);\n if (abs_num > ans && seen[-num + 1024]) ans = abs_num;\n seen[num + 1024] = true;\n }\n return ans ?: -1;\n }\n```\n\nThe complexity is the same as approach 3.\n\n### Approach 6: sort and two pointers\n\nThis is a variation of a solution for the two sum problem, but we have to sort the input first. Note that all the other approach don\'t modify ```nums```.\n\n```cpp\n static int findMaxK(vector<int>& nums) {\n sort(begin(nums), end(nums));\n int lo = 0;\n int hi = size(nums) - 1;\n while (lo < hi) {\n if (-nums[lo] == nums[hi]) {\n return nums[hi];\n } else if (-nums[lo] > nums[hi]) {\n ++lo;\n } else {\n --hi;\n }\n }\n return -1;\n }\n```\n\n**Complexity Analysis**\n * Time complexity: $$O(n \\log n)$$ for the ```std::sort```ing the rest is linear.\n * Space complexity: $$O(\\log n)$$ for the quicksort part of ```std::sort```.\n\n_As always: Feedback, questions, and comments are welcome. Leaving an upvote sparks joy! :)_\n\n**p.s. Join us on the [LeetCode The Hard Way Discord Server](https://discord.gg/hFUyVyWy2E)!**\n
20
0
['Two Pointers', 'C', 'Sorting', 'C++']
8
largest-positive-integer-that-exists-with-its-negative
✅Beats 96% |🔥 Easy, Fast and Efficient using HashSet🔥🔥O(n) time and space complexity 🔥2 pass🔥
beats-96-easy-fast-and-efficient-using-h-cudn
\n\n\n\n# Intuition\nTo find the largest positive integer k such that -k also exists in the array, we can make array into hashset so that search takes O(1) time
Saketh3011
NORMAL
2024-05-02T00:31:06.008861+00:00
2024-05-02T19:21:39.401774+00:00
6,390
false
![image.png](https://assets.leetcode.com/users/images/cd3d80f3-90f6-412f-b227-6a4b013d3e6e_1714609588.3805377.png)\n\n\n\n# Intuition\nTo find the largest positive integer k such that -k also exists in the array, we can make array into hashset so that search takes O(1) time complexity. And iterate through the hashset and check if the negative complement of each number exists in the hashset. Storing max number satisfying given condition.\n\n# Approach\nWe can use a set to efficiently check for the existence of numbers in the array. We initialize the result variable `res` to -1 incase no number is found satisfying giving condition and iterate through the set of numbers in the array. For each number `num`, we check if its negative counterpart `-num` exists in the array. If it does, we update the result `res` to be the maximum of the current `res` and `num`.\n\n# Complexity\n- Time complexity: $$O(n)$$, where n is the number of elements in the array. The loop iterates through the array once.\n- Space complexity: $$O(n)$$, due to the set `nums`, which stores the distinct elements of the array.\n\n\n# Code\n``` python []\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n res = -1\n nums = set(nums)\n for num in nums:\n if num * -1 in nums:\n res = max(res, num)\n return res\n```\n```java []\nclass Solution {\n public int findMaxK(int[] nums) {\n int res = -1;\n Set<Integer> numSet = new HashSet<>();\n for (int num : nums) {\n numSet.add(num);\n }\n for (int num : numSet) {\n if (numSet.contains(-num)) {\n res = Math.max(res, num);\n }\n }\n return res;\n }\n};\n```\n```cpp []\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n int res = -1;\n std::unordered_set<int> numSet(nums.begin(), nums.end());\n for (int num : numSet) {\n if (numSet.find(-num) != numSet.end()) {\n res = std::max(res, num);\n }\n }\n return res;\n }\n};\n```\n``` javascript []\nvar findMaxK = function(nums) {\n let res = -1;\n let numSet = new Set(nums);\n for (let num of numSet) {\n if (numSet.has(-num)) {\n res = Math.max(res, num);\n }\n }\n return res;\n};\n```
16
2
['Python', 'C++', 'Java', 'Python3', 'JavaScript']
9
largest-positive-integer-that-exists-with-its-negative
☠💀💯 Faster✅💯 Lesser🧠 🎯 C++✅Python3✅Java✅C✅Python✅C#✅💥🔥💫Explained☠💥🔥 Beats 💯
faster-lesser-cpython3javacpythoncexplai-1wu2
Intuition\n\n\n\nC++ []\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n int low = 0, high =
Edwards310
NORMAL
2024-05-02T01:58:50.792625+00:00
2024-05-02T08:55:42.358782+00:00
1,967
false
# Intuition\n![0ehh83fsnh811.jpg](https://assets.leetcode.com/users/images/9686e2e9-bde0-4d3d-9b04-cf798bc2b85b_1714614972.0940583.jpeg)\n![Screenshot 2024-05-02 072514.png](https://assets.leetcode.com/users/images/d61d1156-f949-4960-b288-13585cf68727_1714614981.1707056.png)\n![Screenshot 2024-05-02 072549.png](https://assets.leetcode.com/users/images/31f1e039-558d-46b0-8d72-9dccf5d951aa_1714614987.5647128.png)\n```C++ []\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n int low = 0, high = nums.size() - 1;\n\n while (low < high) {\n if ((nums[low] + nums[high]) == 0) {\n return nums[high];\n }\n else if ((nums[low] + nums[high]) < 0)\n low++;\n else\n high--;\n }\n return -1;\n }\n};\n```\n```python3 []\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n sm = [0] * 1001\n maxi = -1\n for n in nums:\n idx = n if n > 0 else -n\n if sm[idx] != n:\n sm[idx] += n\n if sm[idx] == 0:\n maxi = maxi if maxi > idx else idx\n return maxi\n```\n```C# []\npublic class Solution {\n public int FindMaxK(int[] nums) {\n Array.Sort(nums);\n int j = nums.Length - 1, i = 0;\n while (i < j) {\n int a = -1 * nums[j];\n if (nums[i] == a)\n return nums[j];\n else if (nums[i] < a)\n i++;\n else\n j--;\n }\n return -1;\n }\n}\n```\n```Java []\nclass Solution {\n public int findMaxK(int[] nums) {\n Arrays.sort(nums);\n int j = nums.length - 1, i = 0;\n while (i < j) {\n int a = -1 * nums[j];\n if (nums[i] == a)\n return nums[j];\n else if (nums[i] < a)\n i++;\n else\n j--;\n }\n return -1;\n }\n}\n```\n```python []\nclass Solution(object):\n def findMaxK(self, nums):\n """\n :type nums: List[int]\n :rtype: int\n """\n k = -1\n nums_set = set(nums)\n for n in nums:\n if n > 0:\n if n > k and -n in nums_set:\n k = n\n\n\n return k\n```\n```C []\nint cmpfunc(const void* a, const void* b) { \n return (*(int*)a - *(int*)b);\n }\nint findMaxK(int* nums, int numsSize) {\n qsort(nums, numsSize, sizeof(int), cmpfunc);\n int j = numsSize - 1, i = 0;\n while (i < j) {\n int a = -1 * nums[j];\n if (nums[i] == a)\n return nums[j];\n else if (nums[i] < a)\n i++;\n else\n j--;\n }\n return -1;\n}\n```\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(nlogn)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n# Code\n```\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n int low = 0, high = nums.size() - 1;\n\n while (low < high) {\n if ((nums[low] + nums[high]) == 0) {\n return nums[high];\n }\n else if ((nums[low] + nums[high]) < 0)\n low++;\n else\n high--;\n }\n return -1;\n }\n};\n```
14
0
['Array', 'Hash Table', 'Two Pointers', 'C', 'Python', 'C++', 'Java', 'Python3', 'C#']
7
largest-positive-integer-that-exists-with-its-negative
JAVA, JAVASCRIPT || 100% FASTER || 4LINE CODE
java-javascript-100-faster-4line-code-by-05hw
PLEASE UPVOTE IF YOU LIKE IT\n# Complexity\n- Time complexity:O(N)\n- Space complexity:O(N)\n\n# Code\nJAVA\n\nclass Solution {\n public int findMaxK(int[] a
sharforaz_rahman
NORMAL
2023-05-17T14:23:29.080544+00:00
2023-05-17T14:23:29.080583+00:00
1,097
false
**PLEASE UPVOTE IF YOU LIKE IT**\n# Complexity\n- Time complexity:O(N)\n- Space complexity:O(N)\n\n# Code\n**JAVA**\n```\nclass Solution {\n public int findMaxK(int[] arr) {\n HashMap<Integer, Integer> map = new HashMap<>();\n int max = -1;\n for (int i : arr) {\n if (map.containsKey(i * -1)) {\n max = Math.max(max, Math.abs(i));\n }\n map.put(i, 0);\n }\n return max;\n }\n}\n```\n**C++**\n```\n#include <unordered_map>\n#include <algorithm>\n\nint findMaxK(int arr[], int size) {\n std::unordered_map<int, int> map;\n int max = -1;\n for (int i = 0; i < size; i++) {\n if (map.count(arr[i] * -1)) {\n max = std::max(max, std::abs(arr[i]));\n }\n map[arr[i]] = 0;\n }\n return max;\n}\n```\n**JAVASCRIPT**\n```\nvar findMaxK = function(arr) {\n const map = new Map()\n let max = -1;\n for(let i of arr){\n if(map.has(i * -1)){\n max = Math.max(max,Math.abs(i))\n }\n map.set(i, 0)\n }\n return max;\n};\n```
11
0
['Hash Table', 'C++', 'Java', 'JavaScript']
4
largest-positive-integer-that-exists-with-its-negative
✅ [Python/Rust] fastest (100%) using two pointers, binary search (with detailed comments)
pythonrust-fastest-100-using-two-pointer-p4r2
IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE.\n\nPython. This solution employs sorting and a two-pointers approach. It demonstrated 127 ms runtime (100.00%) and use
stanislav-iablokov
NORMAL
2022-10-16T04:02:09.448806+00:00
2022-10-23T12:37:11.982549+00:00
837
false
**IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE.**\n\n**Python.** This [**solution**](https://leetcode.com/submissions/detail/823480874/) employs sorting and a two-pointers approach. It demonstrated **127 ms runtime (100.00%)** and used **14.2 MB memory (33.33%)**. Time complexity is log-linear (due to sorting): **O(N\\*logN)**. Space complexity is constant (in-place operations): **O(1)**. \n```\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n \n # [1] two use two-pointers approach, we need\n # to prepare the list by sorting\n nums.sort()\n \n # [2] move pointers towards each other to find\n # largest positive integer with its negative\n i, j = 0, len(nums)-1\n while i < j:\n if nums[i] == - nums[j]:\n return nums[j]\n if abs(nums[i]) > abs(nums[j]):\n i += 1\n else:\n j -= 1\n \n return -1\n```\n\n**Rust.** This [**solution**](https://leetcode.com/submissions/detail/823474467/) employs sorting and binary search. It demonstrated **0 ms runtime (100.00%)** and used **2.0 MB memory (100.00%)**. Time complexity is log-linear (due to sorting): **O(N\\*logN)**. Space complexity is constant (in-place operations): **O(1)**. \n```\nimpl Solution \n{\n pub fn find_max_k(mut nums: Vec<i32>) -> i32 \n {\n // [1] to use binary search, we need\n // to prepare the list by sorting\n nums.sort();\n \n // [2] now we can move from the right\n // and make binary search queries\n for i in (0..nums.len()).rev()\n {\n match nums.binary_search(&(-nums[i]))\n {\n Ok(j) => return nums[i],\n _ => {}\n }\n }\n return -1;\n }\n}\n```
11
0
['Python', 'Rust']
3
largest-positive-integer-that-exists-with-its-negative
✅✅✅ C++ using Vector || Very Simple and Easy to Understand Solution
c-using-vector-very-simple-and-easy-to-u-td94
Up Vote if you like the solution\n\n/*\nSimply consider an array of size 1001, then keep on updating each nth index with value of n,\nWhile placing value of n
kreakEmp
NORMAL
2022-10-16T04:00:29.350599+00:00
2022-10-16T04:30:42.120574+00:00
1,183
false
<b>Up Vote if you like the solution\n```\n/*\nSimply consider an array of size 1001, then keep on updating each nth index with value of n,\nWhile placing value of n in array, keep on checking if it has already a number with opposite\nsign is present or not. if present then take it as ans if it greater then prev ans \n*/\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n int ans = -1;\n vector<int> v(10001, 0);\n for(auto n: nums){\n if( v[abs(n)] != 0 && (v[abs(n)] + n == 0) ) ans = max(ans, abs(n));\n else v[abs(n)] = n;\n }\n return ans;\n }\n};\n```
10
3
[]
5
largest-positive-integer-that-exists-with-its-negative
🔥 4 lines of simple code 3 approaches fully explained ✅|| Easy to understand👍 || Beat 96% users🚀
4-lines-of-simple-code-3-approaches-full-8976
Intuition\n# Brute Force :\nPython3 []\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n c=-1\n for i in nums:\n i=i*
siddharth-kiet
NORMAL
2024-05-02T07:52:22.703098+00:00
2024-05-02T18:24:56.400582+00:00
1,503
false
# Intuition\n# Brute Force :\n```Python3 []\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n c=-1\n for i in nums:\n i=i*-1\n if i in set(nums) and i>c: c=i\n return c\n```\n```Python []\nclass Solution(object):\n def findMaxK(self, nums):\n """\n :type nums: List[int]\n :rtype: int\n """\n c=-1\n for i in nums:\n i=i*-1\n if i in set(nums) and i>c: c=i\n return c\n```\n```C++ []\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n int c=-1;\n for(int i=0;i<nums.size();i++){\n int n=(nums[i]*-1);\n if((find(nums.begin(),nums.end(),n)!=nums.end()) && n>c){\n c=n;\n }\n }\n return c;\n }\n};\n```\n**Python, Python3 and C++ :**\n1. **Initialization :** The variable **\'c\'** is initialized to -1.\n2. **Iteration through the list nums :** The code iterates through each element **\'i\'** in the input list **\'nums\'**.\n3. **Negating elements :** Each element **nums[i]** is negated by multiplying it by -1 **(int n = (nums[i] * -1))**. This effectively changes each element to its negative counterpart(simply changes positive number to negative and negative number to positive).\n4. **Checking existence and updating c:** It checks if the negated element **i** exists in the original list **nums** using a set to perform a membership test **(i in set(nums))** in python and **(find(nums.begin(), nums.end(), n) != nums.end())** in c++ . Additionally, it checks if the negated element is greater than the current maximum integer **c**. If both conditions are met, **c** is updated to the current negated element **i**.\n5. Finally return c.\n\n**There is a another brute force method which reduce the time complexity to O(n)**\n```Python3 []\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n c=-1\n nums=set(nums)\n for i in nums:\n i=i*-1\n if i in nums and i>c: c=i\n return c\n```\n```Python []\nclass Solution(object):\n def findMaxK(self, nums):\n """\n :type nums: List[int]\n :rtype: int\n """\n c=-1\n nums=set(nums)\n for i in nums:\n i=i*-1\n if i in nums and i>c: c=i\n return c\n```\n```C++ []\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n int c=-1;\n unordered_set<int> s(nums.begin(),nums.end());\n for(int i:s){\n int n=(i*-1);\n if((find(s.begin(),s.end(),n)!=s.end()) && n>c){\n c=n;\n }\n }\n return c;\n }\n};\n```\nIn above code we just convert the **nums** to the **set** so the **in** and **find** operations takes O(1) time complexity in **set** so overall time complexity will be O(n).\n\n\n# Hashing or Counting Approach :\n```Python3 []\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n c=-1\n nums=list(set(nums))\n for i in range(len(nums)):\n if nums[i]<0:\n nums[i]=nums[i]*-1\n co=Counter(nums)\n for i,j in co.items():\n if j==2 and i>c:\n c=i\n return c\n```\n```Python []\nclass Solution(object):\n def findMaxK(self, nums):\n """\n :type nums: List[int]\n :rtype: int\n """\n c=-1\n nums=list(set(nums))\n for i in range(len(nums)):\n if nums[i]<0:\n nums[i]=nums[i]*-1\n co=Counter(nums)\n for i,j in co.items():\n if j==2 and i>c:\n c=i\n return c\n```\n```C++ []\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n set<int> s(nums.begin(),nums.end());\n vector<int> num(s.begin(),s.end());\n int c=-1;\n for(int i=0; i<num.size(); i++){\n if (num[i]<0){\n num[i]*=-1;\n }\n }\n map<int,int> m;\n for(int i:num){\n m[i]++;\n }\n for(auto i:m){\n if(i.second>1 && i.first>c){\n c=i.first;\n }\n }\n return c;\n }\n};\n```\n**Python and Python3 :**\n1. **Initialization :** Variable **c** is initialized to -1.\n2. **Removing Duplicates :** The list **nums** is converted to a set to remove duplicates, then converted back to a list. This ensures that each unique element appears only once in the list.\n3. **Negating Elements :** The code iterates through the indices of the list **nums**. If the element at index **i** is negative, it is negated (multiplied by -1).Simply it converts the whole **nums** elements into positive integers.\n4. **Counting Frequencies :** A Counter object **co** is created to count the frequency of each element in the modified **nums** list.\n5. **Finding the Maximum :** The code iterates through the items of the Counter object. If the frequency of an element is 2 (indicating it occurs twice) and the element is greater than the current maximum integer **c**, **c** is updated to that element.\n6. Finally return **c**.\n\n**C++ :**\n1. **Set Creation :** It creates a set **s** from the input vector **nums** to remove duplicates and store unique elements.\n2. **Vector Conversion :** It converts the set **s** back to a vector **num**. This conversion ensures that **num** contains only unique elements from **nums**.\n3. **Initialization :** It initializes **c** to -1.\n4. **Negating Elements :** It iterates through the vector **num** and negates negative elements by multiplying them by -1.\n5. **Map Creation and Frequency Counting :** It creates a map **m** to count the frequency of elements in **num**. It then iterates through **num** and updates the count of each element in **m**.\n6. **Finding the Maximum :** It iterates through the map **m** and find If an element occurs more than once **(i.second > 1)** and is greater than the current maximum integer **c**, **c** is updated to that element.\n7. Finally return **c**.\n\n# Sorting :\n \n```Python3 []\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n c=-1\n nums=list(set(nums))\n for i in range(len(nums)):\n if nums[i]<0:\n nums[i]=nums[i]*-1\n nums.sort()\n for i in range(len(nums)-1):\n if nums[i]==nums[i+1] and nums[i]>c:\n c=nums[i]\n return c\n```\n```Python []\nclass Solution(object):\n def findMaxK(self, nums):\n """\n :type nums: List[int]\n :rtype: int\n """\n c=-1\n nums=list(set(nums))\n for i in range(len(nums)):\n if nums[i]<0:\n nums[i]=nums[i]*-1\n nums.sort()\n for i in range(len(nums)-1):\n if nums[i]==nums[i+1] and nums[i]>c:\n c=nums[i]\n return c\n```\n```C++ []\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n set<int> s(nums.begin(),nums.end());\n vector<int> num(s.begin(),s.end());\n int c=-1;\n for(int i=0; i<num.size(); i++){\n if (num[i]<0){\n num[i]*=-1;\n }\n }\n sort(num.begin(),num.end());\n for(int i=0;i<num.size()-1;i++){\n if(num[i]==num[i+1] && num[i]>c){\n c=num[i];\n }\n }\n return c;\n }\n};\n```\n**Python, Python3 and C++ :**\n1. **Initialization :** Variable **c** is initialized to -1.\n2. **Removing Duplicates :** The list **nums** is converted to a set to remove duplicates, then converted back to a list. This ensures that each unique element appears only once in the list.\n3. **Negating Elements :** The code iterates through the indices of the list **nums**. If the element at index **i** is negative, it is negated (multiplied by -1).\n4. **Sorting :** The list **nums** is sorted in ascending order using the sort() method.\n5. **Finding Maximum :** The code iterates through the indices of the sorted list **nums** up to the second last element. If the current element is equal to the next element(by sorting the elements the elements which is twice in numbers are come next to each other so it helps to check same elements easily) and greater than **c**, **c** is updated to the current element.\n6. Finally return **c**.\n\n\n# Approach : Brute Force, Hashing or Counting and Sorting\n\n# Complexity\n- Time complexity: O(n) in Counting, O(nlogn) in Sorting and O(n^2) and O(n) in Brute Force\n\n- Space complexity: O(1) and O(n) in Brute Force, O(m) in Sorting and Counting where m is the unique elements in **\'nums\'** vector.\n\nI hope you understand the code \uD83D\uDE4F and if you have any query let me know in the comment and tell me which approach you like the most.\nFinally Thanks you all for visiting here.
8
0
['Array', 'Hash Table', 'Two Pointers', 'Ordered Map', 'Sorting', 'Python', 'C++', 'Python3']
1
largest-positive-integer-that-exists-with-its-negative
Python3 || O(n) TIME AND SPACE || May 2 2024 Daily
python3-on-time-and-space-may-2-2024-dai-o222
Intuition\nThe problem requires finding the largest positive integer k such that -k also exists in the given array nums. To solve this, we can use a set to effi
praneelpa
NORMAL
2024-05-02T01:10:57.877822+00:00
2024-05-02T02:51:56.588581+00:00
799
false
# Intuition\nThe problem requires finding the largest positive integer k such that -k also exists in the given array nums. To solve this, we can use a set to efficiently check for the existence of the negation of each number in the array.\n\n# Approach\nInitialize a variable ans to store the result and a set seen to store the numbers encountered so far. Iterate through each number num in the nums array. Check if the negation of the current number -num exists in the seen set. If it does, update ans to the maximum of its current value and the absolute value of num. Otherwise, add num to the seen set. After iterating through all numbers in the array, return ans as the result.\n\n# Complexity\n- Time complexity:\nThe time complexity of this solution is O(n), where n is the length of the input array `nums`. This is because we iterate through the array once, and each set operation (addition and checking for existence) takes O(1) time on average.\n\n- Space complexity:\nThe space complexity is also O(n) because we use a set `seen` to store the unique numbers encountered in the array. In the worst case, the set could contain all elements of the array.\n\n# Code\n```\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n ans = -1\n seen = set()\n\n for num in nums:\n if -num in seen:\n ans = max(ans, abs(num))\n else:\n seen.add(num)\n\n return ans\n```
7
0
['Array', 'Hash Table', 'Two Pointers', 'Sorting', 'Python3']
6
largest-positive-integer-that-exists-with-its-negative
Python | Easy Solution✅
python-easy-solution-by-gmanayath-5v9u
Code\u2705\n\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n pos, neg= set(), set()\n for digit in nums:\n pos.add(
gmanayath
NORMAL
2023-02-02T04:30:17.378553+00:00
2023-02-02T04:30:17.378595+00:00
964
false
# Code\u2705\n```\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n pos, neg= set(), set()\n for digit in nums:\n pos.add(digit) if digit > 0 else neg.add(digit)\n \n for digit in sorted(pos,reverse = True):\n if (digit*-1) in neg:\n return digit\n return -1\n```
7
0
['Python', 'Python3']
4
largest-positive-integer-that-exists-with-its-negative
C++|| Simple Solution with small optimization || Beats 99.24%
c-simple-solution-with-small-optimizatio-bfif
\n\n# Approach\n Describe your approach to solving the problem. \nSort the array. \ntake two pointers i and j where i wil keep track of negative numbers and j w
prajnanam
NORMAL
2024-05-02T03:15:45.854256+00:00
2024-05-02T05:03:57.184608+00:00
1,027
false
\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSort the array. \ntake two pointers i and j where i wil keep track of negative numbers and j will keep track of positive numbers.\nif(nums[i]+nums[j] < 0) that means abs(nums[i]) is > nums[j] so we move i pointer forward.\nif(nums[i]+nums[j] > 0) that means abs(nums[i]) is < nums[j] so we move j pointer forward.\nif sum becomes zero that means -k+k=0 so k will be my answer or nums[j] will be my answer.\n\n**Small optimization:**\nif nums[i] becomes > 0 we return -1 bcoz nums[j] is >0 and nums[i]>0 we cant find the answer in this case.\nSimilarly if nums[j] becomes < 0 we return -1 bcoz nums[i] is < 0.\n\n# Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n if(nums[0]>0 || nums[nums.size()-1] <0) return -1;\n int i=0,j=nums.size()-1;\n while(i<j){\n if(nums[i]+nums[j] == 0) return nums[j];\n else if((nums[i]+nums[j]) < 0) i++;\n else j--;\n\n if(nums[i] >0 || nums[j]<0) break;\n }\n return -1;\n }\n};\n```
6
0
['Two Pointers', 'Sorting', 'C++']
1
largest-positive-integer-that-exists-with-its-negative
Java Easiest Solution
java-easiest-solution-by-janhvi__28-dmzc
\nclass Solution {\n public int findMaxK(int[] nums) {\n Arrays.sort(nums);\n for (int i = 0; i < nums.length; i++) {\n for (int j =
Janhvi__28
NORMAL
2022-10-18T16:20:33.619166+00:00
2022-10-18T16:20:33.619204+00:00
427
false
```\nclass Solution {\n public int findMaxK(int[] nums) {\n Arrays.sort(nums);\n for (int i = 0; i < nums.length; i++) {\n for (int j = nums.length-1; j>=0; j--) {\n if(nums[i]+nums[j]==0)return nums[j];\n }\n }\n return -1;\n }\n}\n```
6
0
['Java']
2
largest-positive-integer-that-exists-with-its-negative
Short JavaScript Solution Using a Set Object
short-javascript-solution-using-a-set-ob-6jzm
Found this solution helpful? Consider showing support by upvoting this post.\nHave a question? Kindly leave a comment below.\nThank you and happy hacking!\n\nco
sronin
NORMAL
2022-10-16T18:32:59.105994+00:00
2022-10-17T12:09:49.740109+00:00
471
false
Found this solution helpful? Consider showing support by upvoting this post.\nHave a question? Kindly leave a comment below.\nThank you and happy hacking!\n```\nconst findMaxK = (nums) => {\n let numsSet = new Set(nums)\n let largestInteger = -Infinity\n\n for (let num of numsSet) {\n if (num > 0 && numsSet.has(-num)) {\n largestInteger = Math.max(largestInteger, num)\n }\n }\n\n return largestInteger === -Infinity ? -1 : largestInteger\n};\n```
6
0
['JavaScript']
1
largest-positive-integer-that-exists-with-its-negative
Java Two Solutions using sorting and hash Set
java-two-solutions-using-sorting-and-has-fm6g
Solution one, using sorting and hashset..\nFirst, the array is sorted in ascending order and all the elements of the array are stored in a hashset. Then the sor
Abhinav_0561
NORMAL
2022-10-16T08:15:18.175130+00:00
2022-10-16T08:26:32.874086+00:00
848
false
Solution one, using sorting and hashset..\nFirst, the array is sorted in ascending order and all the elements of the array are stored in a hashset. Then the sorted array is traversed from the end to the 0 index and whenever we found an element whose negative is also present in the hash set, we return the ans. Else returning -1 in the end.\n```\nclass Solution {\n public int findMaxK(int[] nums) {\n Arrays.sort(nums);\n HashSet<Integer> set = new HashSet<>();\n for(int i = 0 ; i < nums.length ; i++){\n set.add(nums[i]);\n }\n for(int i = nums.length-1; i>=0 ; i--){//Checking the largest numbers from the last index as the array is sorted\n if(set.contains(-nums[i])){\n return nums[i];\n }\n }\n return -1;\n }\n}\n```\nTime Complexity: O(n Log n) \nNow optimizing the code...\nFirst traversing the entire array and adding all the elements in the hash set. Then initially assuming the ans as -1, iterating through the array and checking for every element whether it is greater than the current ans and its negative is also present in the hash set. Returning this answer variable in the end.\n```\nclass Solution {\n public int findMaxK(int[] nums) {\n Set<Integer> set = new HashSet<>();\n for (int i = 0; i < nums.length; i++){\n set.add(nums[i]);\n\t\t\t}\n int ans = -1;\n for (int i = 0; i < nums.length; i++) {\n if (nums[i] > ans && set.contains(-nums[i]))\n ans = nums[i];\n }\n return ans;\n }\n}\n```\nTime Complexity: O(n)
6
0
['Sorting', 'Java']
3
largest-positive-integer-that-exists-with-its-negative
5 line Code||Easy Understanding||Beginner level
5-line-codeeasy-understandingbeginner-le-z1b4
Please upvote to motivate me in my quest of documenting all leetcode solutions. HAPPY CODING:)\nAny suggestions and improvements are always welcome.\n___\n__\nQ
Anos
NORMAL
2022-10-16T06:21:29.234286+00:00
2022-10-16T06:21:29.234320+00:00
521
false
***Please upvote to motivate me in my quest of documenting all leetcode solutions. HAPPY CODING:)\nAny suggestions and improvements are always welcome*.**\n___________________\n_________________\n***Q2441. Largest Positive Integer That Exists With Its Negative***\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\n\u2705 **Python Code** :\n```\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n a=sorted(set(nums))\n m=0\n for i in nums:\n if -i in a:\n m=max(m,i)\n return m if m!=0 else -1\n```\n____________________________________________________________________________________________________________________\n____________________________________________________________________________________________________________________\nIf you like the solution, please upvote \uD83D\uDD3C\nFor any questions, or discussions, comment below. \uD83D\uDC47\uFE0F\n
6
0
['Python']
2
largest-positive-integer-that-exists-with-its-negative
Python O(n)
python-on-by-diwakar_4-6koh
Complexity\n- Time complexity: O(nlog2n))\n- Space complexity: O(n)\n\n# Code\n\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n d = {
diwakar_4
NORMAL
2022-10-16T04:09:57.386796+00:00
2022-10-16T04:41:46.772129+00:00
459
false
# Complexity\n- Time complexity: O(nlog<sub>2</sub>n))\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n d = {}\n for i in nums:\n d[i] = d.get(i, 0)+1\n \n ans = -1\n for i in sorted(d.keys()):\n if i<0:\n continue\n elif i>0 and -i in d:\n ans = i\n \n return ans\n```\n--------\n**Upvote the post if you find it helpful.\nHappy coding.**
6
1
['Python3']
2
largest-positive-integer-that-exists-with-its-negative
💯JAVA Solution Explained in HINDI (4 Approaches)
java-solution-explained-in-hindi-4-appro-kvwt
https://youtu.be/6fkCZNSwC6s\n\nFor explanation, please watch the above video and do like, share and subscribe the channel. \u2764\uFE0F Also, please do upvote
The_elite
NORMAL
2024-05-02T13:05:02.948628+00:00
2024-05-02T13:05:02.948654+00:00
869
false
https://youtu.be/6fkCZNSwC6s\n\nFor explanation, please watch the above video and do like, share and subscribe the channel. \u2764\uFE0F Also, please do upvote the solution if you liked it.\n\n# Subscribe link:- [ReelCoding](https://www.youtube.com/@reelcoding?sub_confirmation=1)\n\nSubscribe Goal:- 400\nCurrent Subscriber:- 351\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int findMaxK(int[] nums) {\n boolean[] vis = new boolean[2001];\n int ans = -1;\n \n for (int el : nums) {\n if (vis[-el + 1000]) ans = Math.max(ans, Math.abs(el));\n vis[el + 1000] = true;\n }\n \n return ans; \n\n }\n}\n```\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n```\nclass Solution {\n public int findMaxK(int[] nums) {\n HashSet<Integer> s = new HashSet<>();\n int ans = -1;\n \n for (int el : nums) {\n if (s.contains(-el)) ans = Math.max(ans, Math.abs(el));\n s.add(el);\n }\n \n return ans; \n }\n}\n```\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n```\nclass Solution {\n public int findMaxK(int[] nums) {\n HashSet<Integer> neg = new HashSet<>();\n\n for (int el : nums) {\n if (el < 0) neg.add(el);\n }\n\n int ans = -1;\n for (int el : nums) {\n if (el > 0 && el > ans && neg.contains(-el)) {\n ans = el;\n }\n }\n \n return ans; \n }\n}\n```\n# Complexity\n- Time complexity: O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n```\nclass Solution {\n public int findMaxK(int[] nums) {\n Arrays.sort(nums);\n\n int i = 0, j = nums.length - 1;\n while (i < j) {\n if (-nums[i] == nums[j]) return nums[j];\n else if (-nums[i] > nums[j]) i++;\n else j--;\n }\n\n return -1;\n }\n}\n```
5
0
['Java']
0
largest-positive-integer-that-exists-with-its-negative
✅ One Line Solution
one-line-solution-by-mikposp-xjys
(Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)\n\n# Code #1\nTime complexity: O(n). Space complexi
MikPosp
NORMAL
2024-05-02T08:16:33.992334+00:00
2024-05-02T08:16:33.992352+00:00
890
false
(Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)\n\n# Code #1\nTime complexity: $$O(n)$$. Space complexity: $$O(n)$$.\n```\nclass Solution:\n def findMaxK(self, a: List[int]) -> int:\n return max(filter(lambda v:-v in d,d:={*a}),default=-1)\n```\n\n# Code #2\nTime complexity: $$O(n*log(n))$$. Space complexity: $$O(n)$$.\n```\nclass Solution:\n def findMaxK(self, a: List[int]) -> int:\n return next((abs(v) for v,u in pairwise(sorted(a,key=abs)[::-1]) if v==-u),-1)\n```\n\n(Disclaimer 2: all code above is just a product of fantasy, it is not claimed to be pure impeccable oneliners - please, remind about drawbacks only if you know how to make it better. PEP 8 is violated intentionally)
5
0
['Array', 'Hash Table', 'Sorting', 'Python', 'Python3']
1
largest-positive-integer-that-exists-with-its-negative
3 solutions | O(n^2), O(n logn) and O(n) | ✅
3-solutions-on2-on-logn-and-on-by-gurman-zoyt
\n---\n\n# BRUTEFORCE SOLUTION (O(N^2))\n\n---\n\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \nA brute force approach involves c
gurmankd
NORMAL
2024-05-02T04:40:38.678036+00:00
2024-05-02T04:42:24.543047+00:00
11
false
\n---\n\n# BRUTEFORCE SOLUTION $$(O(N^2))$$\n\n---\n\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nA brute force approach involves checking every pair of elements in the array to see if their absolute values are equal. This requires nested loops to compare each element with every other element.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Use nested loops to iterate through each pair of elements in the array.\n2. For each pair, check if the absolute values are equal.\n3. If a pair with equal absolute values is found, update the maximum positive integer `k`.\n4. After checking all pairs, return the maximum positive integer `k` found. If no such pair is found, return `-1`.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n`O(n^2)`, where `n` is the size of the input array. This is because we have nested loops to check each pair of elements.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n`O(1)` since we\'re using constant extra space.\n\n# Code\n```\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n int maxK = -1;\n for (int i = 0; i < nums.size(); ++i) {\n for (int j = i + 1; j < nums.size(); ++j) {\n if (abs(nums[i]) == nums[j]) {\n maxK = max(maxK, nums[i]);\n }\n }\n }\n return maxK;\n }\n};\n\n```\n\n\n---\n\n# SORTING SOLUTION $$(O(N LOG N))$$\n\n---\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo find the largest positive integer `k` such that its negative exists in the given array, we can sort the array and then traverse it from both ends. By doing so, we ensure that we consider both positive and negative numbers. We compare the absolute values of the numbers at the `start` and `end` of the array. If they are equal, we return that value as k. If the absolute value at the `start` is less than the absolute value at the `end`, we move the `end` pointer inward. Otherwise, we move the `start` pointer inward. If we exhaust the array without finding such a pair, we return `-1`.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Sort the array to simplify the search process.\n2. Initialize two pointers, one at the `start` and one at the `end`` of the array.\n3. Traverse the array from both ends:\n- If the absolute value at the `start` equals the value at the `end`, return that value as `k`.\n- If the absolute value at the `start` is less than the value at the `end`, move the `end` pointer inward.\n- If the absolute value at the `start` is greater than the value at the `end`, move the `start` pointer inward.\n4. If no such pair is found, return `-1`.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n`O(nlogn)` due to the sorting step, where `n` is the size of the input array.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n`O(1)` since we\'re using constant extra space.\n\n# Code\n```\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n int start = 0;\n int end = nums.size()-1;\n while(start < end && nums[start] < 0 && nums[end] > 0){\n if(abs(nums[start]) == nums[end]) \n return nums[end];\n else if(abs(nums[start]) < nums[end]) \n end--;\n else\n start++;\n }\n return -1;\n }\n};\n```\n---\n\n# UNORDERED SET SOLUTION $$(O(n))$$\n\n---\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo solve the problem in linear time complexity `O(n)`, we can utilize a hash set to efficiently check for the existence of negative counterparts for each positive integer in the array. By iterating through the array once, we can determine the largest positive integer k such that its negative counterpart exists in the array.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize an `unordered set` to store the numbers encountered in the array.\n2. Iterate through the array once.\n3. For each element in the array:\n- Check if it is a positive integer and if its negative counterpart exists in the set.\n- If both conditions are met, update the maximum positive integer \n`k` found so far.\n- After iterating through the array, return the maximum positive integer \n`k` found. \n4. If no such pair is found, return `-1`.\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n`O(n)`, where `n` is the size of the input array. This is because we iterate through the array once.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n`O(n)` due to the hash set used to store the numbers encountered in the array.\n# Code\n```\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n unordered_set<int> numSet(nums.begin(), nums.end());\n int maxK = -1;\n for (int num : nums) {\n if (num > 0 && numSet.count(-num)) {\n maxK = max(maxK, num);\n }\n }\n return maxK;\n }\n};\n```\n\n---\n\n\n\n
5
0
['Two Pointers', 'Sorting', 'C++']
0
largest-positive-integer-that-exists-with-its-negative
Python | Easy
python-easy-by-khosiyat-lqeu
see the Successfully Accepted Submission\n\n# Code\n\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n # Initialize a set to store the
Khosiyat
NORMAL
2024-05-02T04:36:53.014669+00:00
2024-05-02T04:36:53.014696+00:00
503
false
[see the Successfully Accepted Submission](https://leetcode.com/problems/largest-positive-integer-that-exists-with-its-negative/submissions/1247084199/?envType=daily-question&envId=2024-05-02)\n\n# Code\n```\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n # Initialize a set to store the absolute values of negative numbers\n neg_abs = set()\n \n # Loop through the numbers and insert the absolute values of negative numbers into the set\n for num in nums:\n if num < 0:\n neg_abs.add(-num)\n \n max_k = -1\n \n # Iterate through the numbers to find the maximum positive integer\n for num in nums:\n # If current number is positive and its absolute value exists in the set\n if num > max_k and num in neg_abs:\n max_k = num\n \n return max_k\n\n```\n![image](https://assets.leetcode.com/users/images/b1e4af48-4da1-486c-bc97-b11ae02febd0_1696186577.992237.jpeg)
5
0
['Python3']
0
largest-positive-integer-that-exists-with-its-negative
🗓️ Daily LeetCoding Challenge Day 134|| 🔥 JAVA SOL
daily-leetcoding-challenge-day-134-java-ejvra
Good morning!!\n# Code\n\nclass Solution {\n public int findMaxK(int[] nums) {\n int[] sum = new int[1001];\n int max = -1;\n for (int n
DoaaOsamaK
NORMAL
2024-05-02T04:25:30.725738+00:00
2024-05-02T04:25:30.725761+00:00
249
false
Good morning!!\n# Code\n```\nclass Solution {\n public int findMaxK(int[] nums) {\n int[] sum = new int[1001];\n int max = -1;\n for (int n : nums) {\n int index = n > 0 ? n : -n;\n if (sum[index] != n) {\n sum[index] += n;\n }\n \n if (sum[index] == 0) {\n max = max > index ? max : index;\n }\n }\n return max;\n }\n}\n```
5
0
['Java']
2
largest-positive-integer-that-exists-with-its-negative
C# Concise with Linq
c-concise-with-linq-by-ilya-a-f-vv34
csharp\npublic class Solution\n{\n public int FindMaxK(int[] nums) => nums\n .Where(int.IsNegative)\n .Select(int.Abs)\n .Intersect(nums
ilya-a-f
NORMAL
2024-05-02T01:02:37.688457+00:00
2024-05-02T01:02:37.688475+00:00
177
false
```csharp\npublic class Solution\n{\n public int FindMaxK(int[] nums) => nums\n .Where(int.IsNegative)\n .Select(int.Abs)\n .Intersect(nums.Where(int.IsPositive))\n .DefaultIfEmpty(-1)\n .Max();\n}\n```
5
0
['Hash Table', 'C#']
1
largest-positive-integer-that-exists-with-its-negative
Beats 98% || you wouldn't have thought of this I BET!!
beats-98-you-wouldnt-have-thought-of-thi-7kk6
Intuition\n Describe your first thoughts on how to solve this problem. \n# HEY GUYS WRITING THIS POST TAKES LOT OF EFFORTS , AN UPVOTE WOULD CHEER ME UP FRIEND.
Abhishekkant135
NORMAL
2024-05-02T13:20:24.461327+00:00
2024-05-02T13:20:24.461358+00:00
257
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n# HEY GUYS WRITING THIS POST TAKES LOT OF EFFORTS , AN UPVOTE WOULD CHEER ME UP FRIEND. ALSO GET MY LINKEDIN IN COMMENTS.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n\n1. **Initializing Variables:**\n - `int[] positive = new int[1001]`: Creates an integer array `positive` of size 1001. This array will be used to store the frequency of positive numbers encountered in the `nums` array (assuming all positive numbers are less than 1001).\n - `int[] negative = new int[1001]`: Creates an integer array `negative` of size 1001. This array will be used to store the frequency of negative numbers encountered in the `nums` array (assuming all negative numbers are greater than -1000).\n - `int ans = -1`: Initializes a variable `ans` to store the maximum absolute difference found so far (similar to the previous solution).\n\n2. **Iterating Through the Array:**\n - The `for` loop iterates through each element (`nums[i]`) in the `nums` array.\n\n3. **Handling Positive and Negative Numbers:**\n - The code uses an `if-else` statement to categorize the current element (`nums[i]`).\n - `if (nums[i] > 0)`: Checks if the element is positive.\n - `positive[nums[i]]++`: If positive, increments the frequency count for that specific positive number in the `positive` array.\n - `if (negative[nums[i]] > 0)`: Checks if the negative counterpart of the current element (which would be `-nums[i]`) already has entries in the `negative` array (meaning it has been seen before).\n - If `negative[nums[i]] > 0`, it means a potential absolute difference exists. The maximum absolute difference (`ans`) is updated using `Math.max(ans, nums[i])`. Here, `nums[i]` itself represents the absolute difference because the negative counterpart has already been seen.\n - `else`: If the element is not positive, it\'s treated as negative.\n - `negative[Math.abs(nums[i])]++`: Increments the frequency count for the absolute value (negative counterpart) of the current element in the `negative` array.\n - `if (positive[Math.abs(nums[i])] > 0)`: Checks if the positive counterpart of the current element (which would be `Math.abs(nums[i])`) already has entries in the `positive` array (meaning it has been seen before).\n - If `positive[Math.abs(nums[i])] > 0`, it means a potential absolute difference exists. The maximum absolute difference (`ans`) is updated using `Math.max(ans, -nums[i])`. Here, `-nums[i]` represents the absolute difference because the positive counterpart has already been seen.\n\n4. **Returning the Result:**\n - `return ans`: After iterating through the entire array, `ans` will hold the maximum absolute difference found so far (or -1 if no such difference exists). The code returns this value.\n\n\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- This approach has a time complexity of O(n) due to the single iteration through the array and the constant-time array lookups (assuming the value range is limited).\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\nclass Solution {\n public int findMaxK(int[] nums) {\n int [] positive=new int [1001];\n int [] negative=new int [1001];\n int ans=-1;\n for(int i=0;i<nums.length;i++){\n if(nums[i]>0){\n positive[nums[i]]++;\n if(negative[nums[i]]>0){\n ans=Math.max(ans,nums[i]);\n }\n }\n else{\n negative[Math.abs(nums[i])]++;\n if(positive[Math.abs(nums[i])]>0){\n ans=Math.max(ans,-nums[i]);\n }\n }\n }\n return ans;\n }\n}\n```
4
0
['Array', 'Java']
1
largest-positive-integer-that-exists-with-its-negative
Hash table solution
hash-table-solution-by-drgavrikov-0znd
Approach\n Describe your approach to solving the problem. \nThe idea is to use a hash table for constant-time element lookup. We iterate through the array, and
drgavrikov
NORMAL
2024-05-02T08:05:50.549850+00:00
2024-06-02T07:52:10.455791+00:00
20
false
# Approach\n<!-- Describe your approach to solving the problem. -->\nThe idea is to use a hash table for constant-time element lookup. We iterate through the array, and if there exists a negative counterpart $-num$ for the current element $num$ in the hash table, we update the answer.\n\nThis approach provides fast lookup and efficiently finds the maximum value.\n\n# Complexity\n- Time complexity: $O(n)$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $O(n)$ additional memory for hash table.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int findMaxK(std::vector<int>& nums) {\n int result = -1;\n std::unordered_set<int> set;\n for (const auto& num: nums) {\n if (set.find(-num) != set.end() && abs(num) > result) {\n result = abs(num);\n }\n set.insert(num);\n }\n return result;\n }\n};\n```\n\nMost of my solutions are in [C++](https://github.com/drgavrikov/leetcode-cpp) and [Kotlin](https://github.com/drgavrikov/leetcode-jvm) on my [Github](https://github.com/drgavrikov).
4
0
['Hash Table', 'Memoization', 'C++']
0
largest-positive-integer-that-exists-with-its-negative
Go solution. Beats 96%
go-solution-beats-96-by-upikoth-4kim
Code\n\nfunc findMaxK(nums []int) int {\n alreadySeenNums := map[int]bool{}\n res := -1\n\n for _, num := range nums {\n numAbs := int(math.Abs(
upikoth
NORMAL
2024-05-02T07:24:17.840759+00:00
2024-05-02T07:24:17.840782+00:00
279
false
# Code\n```\nfunc findMaxK(nums []int) int {\n alreadySeenNums := map[int]bool{}\n res := -1\n\n for _, num := range nums {\n numAbs := int(math.Abs(float64(num)))\n\n if numAbs < res {\n continue\n }\n\n if alreadySeenNums[-num] {\n res = numAbs\n } else {\n alreadySeenNums[num] = true\n }\n }\n\n return res\n}\n```\n\nPlease upvote if you found this solution useful
4
0
['Go']
0
largest-positive-integer-that-exists-with-its-negative
💯Faster✅💯 | |unordered set||sorting|| 🔥Python🐍Java☕C++😎
faster-unordered-setsorting-pythonjavac-ercgs
Intuition\n Describe your first thoughts on how to solve this problem. \nSeeking Negatives: Since we\'re looking for pairs of positive and negative integers in
sujalgupta09
NORMAL
2024-05-02T04:45:18.767020+00:00
2024-05-02T04:45:18.767049+00:00
1,070
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSeeking Negatives: Since we\'re looking for pairs of positive and negative integers in the array, one way to approach this problem is to iterate through the array and for each positive number, check if its negative counterpart exists in the array.\nTracking Maximum: While traversing the array, we\'ll keep track of the largest positive integer k for which its negative counterpart -k exists in the array.\nUsing a Set: We use a set data structure to efficiently check if a negative counterpart exists for a given positive number. Sets offer constant-time lookup complexity on average, making this operation fast.\nMaximizing k: As we iterate through the array, whenever we find a positive number num for which -num exists in the set, we compare its absolute value with the current maximum k. If num is greater than the current k, we update k to num.\nReturning the Result: After iterating through the entire array, if we\'ve found a valid k, we return it. Otherwise, we return -1 to indicate that no such k exists.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCreate a set: First, create an unordered set to store all the integers in the input array. This allows for quick lookups to check if a certain integer exists in the array.\nIterate through the array: Traverse through the input array, and for each element num, check if its negative counterpart -num exists in the set. If it does, update the largest_k variable with the maximum of its current value and the absolute value of num.\nReturn the result: After iterating through the entire array, check if largest_k has been updated. If it has, return largest_k. Otherwise, return -1, indicating that there is no valid k in the array.\nHandle edge cases: Ensure the input array is not empty. If it is, return -1 as there are no elements to process.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\no(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\no(n)\n\n# Code\n\n# C++\n```\nclass Solution {\npublic:\n int findMaxK(std::vector<int>& nums) {\n std::unordered_set<int> num_set(nums.begin(), nums.end());\n int largest_k = -1;\n\n for (int num : nums) {\n if (num_set.find(-num) != num_set.end()) {\n largest_k = std::max(largest_k, std::abs(num));\n }\n }\n\n return largest_k != -1 ? largest_k : -1;\n }\n};\n```\n# python\n```\n\nint largest_negative_pair(std::vector<int>& nums) {\n std::unordered_set<int> num_set(nums.begin(), nums.end());\n int largest_k = -1;\n\n for (int num : nums) {\n if (num_set.find(-num) != num_set.end()) {\n largest_k = std::max(largest_k, std::abs(num));\n }\n }\n\n return largest_k != -1 ? largest_k : -1;\n}\n\n```\n# java\n```\nimport java.util.HashSet;\n\nclass Solution {\n public int findMaxK(int[] nums) {\n HashSet<Integer> numSet = new HashSet<>();\n int largestK = -1;\n\n for (int num : nums) {\n numSet.add(num);\n }\n\n for (int num : nums) {\n if (numSet.contains(-num)) {\n largestK = Math.max(largestK, Math.abs(num));\n }\n }\n\n return largestK != -1 ? largestK : -1;\n }\n}\n```
4
0
['Array', 'Two Pointers', 'Sorting', 'Ordered Set', 'Python', 'C++', 'Java']
3
largest-positive-integer-that-exists-with-its-negative
Easy | Multiset | Short and Efficient code
easy-multiset-short-and-efficient-code-b-kwv7
\n\n# Code\n\nclass Solution {\npublic:\n // use of set\n int findMaxK(vector<int>& nums) {\n multiset<int> st;\n for(auto it : nums)\n
YASH_SHARMA_
NORMAL
2024-05-02T04:02:23.734221+00:00
2024-05-02T04:02:23.734252+00:00
119
false
\n\n# Code\n```\nclass Solution {\npublic:\n // use of set\n int findMaxK(vector<int>& nums) {\n multiset<int> st;\n for(auto it : nums)\n {\n st.insert(it);\n }\n\n int ans = -1;\n for(auto it : nums)\n {\n if(it > 0)\n {\n if(st.count(-1*it) > 0)\n {\n ans = max(ans , it);\n }\n }\n }\n\n return ans;\n }\n};\n```
4
0
['Array', 'Ordered Set', 'C++']
0
largest-positive-integer-that-exists-with-its-negative
100% Faster || 3 Approaches || Easy to Understand || Short & Concise
100-faster-3-approaches-easy-to-understa-kg63
Intuition\nWe need to find the largest positive integer k such that its negative counterpart -k exists in the given array. To achieve this, we can iterate throu
gameboey
NORMAL
2024-05-02T00:42:33.531377+00:00
2024-05-02T00:51:17.153481+00:00
37
false
# Intuition\nWe need to find the largest positive integer k such that its negative counterpart -k exists in the given array. To achieve this, we can iterate through the array and keep track of the largest positive integer k encountered so far for which -k also exists in the array.\n\n# Approach: Brute Force\nLet\'s dive into the Naruto-inspired explanation for this approach:\n\nImagine you\'re on a mission to find the strongest ninja in the village, someone whose power level is unmatched, and who has a counterpart with an equal but opposite allegiance.\n\n1. **Setting Out on the Mission**:\n - Equipped with your mission scroll (`vector<int>& nums`), you set out to explore the village and encounter various ninjas along the way.\n\n2. **Surveying the Village**:\n - As you traverse the village, you encounter each ninja one by one (`for(int num : nums)`), carefully observing their power levels.\n\n3. **Identifying Potential Candidates**:\n - As you meet each ninja, you evaluate whether they have the potential to be the strongest ninja (`if(num > maxi)`).\n - However, being the strongest ninja isn\'t enough; they must also have a counterpart with an opposite allegiance somewhere in the village.\n\n4. **Consulting the Scroll**:\n - To determine if a ninja\'s counterpart exists, you consult your mission scroll (`vector<int>& nums`) and search for their opposite counterpart.\n - Using your keen ninja senses, you scan through the scroll, looking for the counterpart with an opposite power level (`-num`).\n\n5. **Claiming Victory**:\n - After meticulously scanning through the entire village and evaluating each ninja\'s strength and allegiance, you finally identify the strongest ninja (`maxi`).\n - With the mission accomplished, you proudly return to the village with news of your success.\n\nIn this approach, you dynamically search through the village as you encounter each ninja, using your mission scroll to determine if a counterpart exists. It\'s like being a skilled ninja scout, using your agility and perception to identify the strongest ninja amidst the village\'s inhabitants.\n\n# Complexity\n- Time complexity: O(n * n)\n\n- Space complexity: O(1)\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n int maxi = -1;\n for(int num : nums) {\n if(num > maxi && find(begin(nums), end(nums), -num) != end(nums)) {\n maxi = num;\n }\n }\n\n return maxi;\n }\n};\n```\n```java []\nclass Solution {\n public int findMaxK(int[] nums) {\n int maxi = -1;\n for(int num : nums) {\n if(num > maxi && contains(nums, -num)) {\n maxi = num;\n }\n }\n\n return maxi;\n }\n\n public boolean contains(int[] nums, int num) {\n for(int i : nums) {\n if(i == num) {\n return true;\n }\n }\n\n return false;\n }\n}\n```\n```python []\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n maxi = -1\n for num in nums :\n if num > maxi and -num in nums :\n maxi = num\n\n return maxi\n```\n```javascript []\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar findMaxK = function(nums) {\n let maxi = -1;\n for(let num of nums) {\n if(num > maxi && nums.includes(-num)) {\n maxi = num;\n }\n }\n\n return maxi;\n};\n```\n# Approach: Two Pointers\nLet\'s explain the approach in a Naruto-inspired way!\n\nImagine you\'re facing an array of ninjas, each with their own power level (represented by the elements of the array). Your mission is to find the most powerful ninja `maxi` who has a counterpart with exactly the same power but opposite allegiance (positive vs. negative).\n\n1. **Sorting the Array**:\n - Before diving into battle, it\'s crucial to arrange the ninjas in ascending order of their power levels. This way, you\'ll have a clear view of the battlefield and can strategize better.\n\n2. **Setting Up the Battle Formation**:\n - You take your position at the center of the battlefield, ready to face off against the opposing forces. You set up two allies, one on your left (`left`) and one on your right (`right`), representing the two ends of the sorted array.\n\n3. **Engaging in Combat**:\n - You begin your search for the most powerful ninja `maxi` by inspecting the pair of ninjas at your allies\' positions.\n - If the ninja on your left has greater power than the ninja on your right, you focus your attention on the left side and move your ally towards the right.\n - Conversely, if the ninja on your right has greater power, you shift your focus to the right side and move your ally towards the left.\n - You continue this back-and-forth movement, gradually narrowing down the search range while keeping an eye out for a ninja whose power matches your ally\'s but with opposite allegiance.\n - If you encounter such a pair, you\'ve found `maxi`! You signal victory and end the battle.\n\n4. **Returning from Battle**:\n - If you\'ve searched through the entire battlefield without finding a matching pair, you return in disappointment, unable to locate `maxi`.\n\nThis approach is efficient because it takes advantage of the sorted order of the array, allowing for a systematic search while minimizing unnecessary comparisons. It\'s like navigating a battlefield strategically, focusing your efforts where they\'re most likely to yield results.\n\n# Complexity\n- Time complexity: O(n * logn)\n\n- Space complexity: O(1)\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n sort(begin(nums), end(nums));\n int left = 0, right = nums.size() - 1;\n \n while(left < right && nums[left] < 0 && nums[right] > 0) {\n if(abs(nums[left]) == nums[right]) {\n return nums[right];\n } else if(abs(nums[left]) > nums[right]) {\n left++;\n } else {\n right--;\n }\n }\n\n return -1;\n }\n};\n```\n```java []\nclass Solution {\n public int findMaxK(int[] nums) {\n Arrays.sort(nums);\n int left = 0, right = nums.length - 1;\n\n while (left < right && nums[left] < 0 && nums[right] > 0) {\n if (Math.abs(nums[left]) == nums[right]) {\n return nums[right];\n } else if (Math.abs(nums[left]) > nums[right]) {\n left++;\n } else {\n right--;\n }\n }\n\n return -1;\n }\n}\n```\n```python []\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n nums.sort()\n left, right = 0, len(nums) - 1\n\n while left < right and nums[left] < 0 and nums[right] > 0:\n if abs(nums[left]) == nums[right]:\n return nums[right]\n elif abs(nums[left]) > nums[right]:\n left += 1\n else:\n right -= 1\n\n return -1\n```\n```javascript []\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar findMaxK = function(nums) {\n nums.sort((a, b) => a - b);\n let left = 0, right = nums.length - 1;\n\n while (left < right && nums[left] < 0 && nums[right] > 0) {\n if (Math.abs(nums[left]) === nums[right]) {\n return nums[right];\n } else if (Math.abs(nums[left]) > nums[right]) {\n left++;\n } else {\n right--;\n }\n }\n\n return -1;\n};\n```\n# Approach: Hash Table\nLet\'s explore the approach used in the code in a Naruto-inspired way:\n\nImagine you\'re embarking on a quest to find the mightiest ninja in the land, whose power level is unmatched and who has an equal but opposite counterpart.\n\n1. **Preparing for the Journey**:\n - Before setting out, you gather intelligence and information about the ninjas scattered across the land. You create a special scroll (`unordered_set<int> st`) to record the power levels of all the ninjas you encounter.\n\n2. **Embarking on the Quest**:\n - Armed with your scroll, you traverse the land, encountering ninjas one by one (`for(int num : nums)`).\n - As you encounter each ninja, you add their power level to your scroll (`st.insert(num)`), ensuring that you have a record of all the ninjas you\'ve seen.\n\n3. **Searching for the Mighty Ninja**:\n - With your scroll in hand, you begin your search for the mightiest ninja `maxi`.\n - You carefully examine each ninja you encounter, comparing their power level to the current mightiest ninja `maxi`.\n - However, you\'re not just looking for any powerful ninja; you\'re searching for one whose counterpart, with opposite allegiance, also exists in the land.\n - You consult your scroll (`st`) to see if the counterpart of the current ninja exists. If it does, and the current ninja\'s power level surpasses the current mightiest ninja `maxi`, you update `maxi` with the new ninja\'s power level.\n\n4. **Claiming Victory**:\n - After traversing the entire land and encountering countless ninjas, you finally stumble upon the mightiest ninja `maxi`, whose power level is unmatched, and whose counterpart exists in the land.\n - You proudly declare victory and return triumphant from your quest.\n\nThis approach is efficient because it leverages the power of the scroll (`unordered_set<int> st`) to keep track of encountered ninjas and quickly determine if a ninja\'s counterpart exists. It\'s like embarking on a quest armed with knowledge and resources, ensuring a successful journey to find the mightiest ninja in the land.\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n unordered_set<int> st;\n int maxi = -1;\n for(int num : nums) {\n st.insert(num);\n }\n\n for(int num : nums) {\n if(num > maxi && st.find(-num) != st.end()) {\n maxi = num;\n }\n }\n\n return maxi;\n }\n};\n```\n```java []\nclass Solution {\n public int findMaxK(int[] nums) {\n Set<Integer> st = new HashSet<>();\n int maxi = -1;\n for (int num : nums) {\n st.add(num);\n }\n\n for (int num : nums) {\n if (num > maxi && st.contains(-num)) {\n maxi = num;\n }\n }\n\n return maxi;\n }\n}\n```\n```python []\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n st = set(nums)\n maxi = -1\n for num in nums:\n if num > maxi and -num in st:\n maxi = num\n \n return maxi\n```\n```javascript []\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar findMaxK = function(nums) {\n const set = new Set(nums);\n let maxi = -1;\n for (let num of nums) {\n if (num > maxi && set.has(-num)) {\n maxi = num;\n }\n }\n return maxi\n};\n```\n![Team 7 Naruro OG manga panel.png](https://assets.leetcode.com/users/images/b19ba454-6389-4378-83ac-e083cdcba542_1714611065.2804859.png)\n\n
4
0
['Array', 'Hash Table', 'Two Pointers', 'C++', 'Java', 'Python3', 'JavaScript']
0
largest-positive-integer-that-exists-with-its-negative
Java Easy Solution Using Two Pointers [ 88.55% ] [ 4ms ]
java-easy-solution-using-two-pointers-88-m5lh
Approach\n1. Sort the input array nums in non-decreasing order.\n2. Initialize two pointers, st at the beginning of the array and lt at the end of the array.\n3
RajarshiMitra
NORMAL
2024-04-16T06:55:30.040742+00:00
2024-06-16T08:32:26.920979+00:00
19
false
# Approach\n1. Sort the input array `nums` in non-decreasing order.\n2. Initialize two pointers, `st` at the beginning of the array and `lt` at the end of the array.\n3. Iterate over the array while `st` is less than or equal to `lt`.\n4. In each iteration:\n - Check if the sum of the elements at `st` and `lt` is greater than zero.\n - If so, decrement `lt` to move towards smaller elements.\n - If the sum is less than zero, increment `st` to move towards larger elements.\n5. If the sum is zero, return the element at `lt`, as it represents the maximum value of `k` such that `-k` is also present in the array.\n6. If no such `k` exists, return -1.\n# Complexity\n- Time complexity:\nO(n log n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\n public int findMaxK(int[] nums) {\n Arrays.sort(nums);\n int st=0;\n int lt=nums.length-1;\n while(st<=lt){\n if((nums[st] + nums[lt]) > 0) lt--;\n else if((nums[st] + nums[lt]) < 0) st++;\n else return nums[lt];\n }\n return -1;\n }\n}\n```\n\n![193730892e8675ebafc11519f6174bee5c4a5ab0.jpeg](https://assets.leetcode.com/users/images/b0c899de-1c4c-48db-9ba9-37c21107d01a_1718526742.1580913.jpeg)\n
4
0
['Java']
0
largest-positive-integer-that-exists-with-its-negative
Java|2 pointer | Easiest solution
java2-pointer-easiest-solution-by-abhish-v0b2
\nclass Solution {\n public int findMaxK(int[] nums) {\n Arrays.sort(nums);\n for (int i = 0; i < nums.length; i++) {\n for (int j =
abhishekalimchandani69
NORMAL
2022-10-18T12:17:44.505548+00:00
2022-10-18T12:17:44.505579+00:00
530
false
```\nclass Solution {\n public int findMaxK(int[] nums) {\n Arrays.sort(nums);\n for (int i = 0; i < nums.length; i++) {\n for (int j = nums.length-1; j>=0; j--) {\n if(nums[i]+nums[j]==0)return nums[j];\n }\n }\n return -1;\n }\n}\n```
4
0
['Two Pointers', 'Java']
3
largest-positive-integer-that-exists-with-its-negative
C++ | 2 Pointers | Easy
c-2-pointers-easy-by-shreyanshxyz-56ac
\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n \n int l = 0;\n int r = nums.
shreyanshxyz
NORMAL
2022-10-16T08:17:17.927147+00:00
2022-10-16T08:17:17.927216+00:00
184
false
```\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n \n int l = 0;\n int r = nums.size() - 1;\n \n while(l < r){\n if(nums[l]*-1 == nums[r]){\n return nums[r];\n } else if (nums[l]*-1 < nums[r]){\n r--;\n } else {\n l++;\n }\n }\n return -1;\n }\n};\n```
4
0
['Two Pointers', 'C']
1
largest-positive-integer-that-exists-with-its-negative
2 pointers
2-pointers-by-flexsloth-mxo6
\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n \n sort(nums.begin() , nums.end());\n int i = 0 , j = nums.size()-1;\n
flexsloth
NORMAL
2022-10-16T04:06:08.489565+00:00
2024-01-21T18:54:29.512865+00:00
976
false
```\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n \n sort(nums.begin() , nums.end());\n int i = 0 , j = nums.size()-1;\n for(int k = 0 ; k < nums.size() ; k++){\n if(-nums[i] == nums[j]) return nums[j];\n else if(-nums[i] > nums[j]) i++;\n else j--;\n }\n return -1;\n }\n};\n```
4
0
['C++']
2
largest-positive-integer-that-exists-with-its-negative
💯Faster🔥Lesser✅🧠Detailed Approach🎯Two Pointer🔥Python🐍
fasterlesserdetailed-approachtwo-pointer-0mn2
Intuition\n Describe your first thoughts on how to solve this problem. \nfor pairing the negative and positive pairs used the logic\n>sum of x and -x is zero\n#
MerinMathew19
NORMAL
2024-05-02T13:05:41.663247+00:00
2024-05-02T13:15:57.796682+00:00
42
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n**for pairing the negative and positive pairs used the logic**\n>sum of x and -x is zero\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**1) Sorted the array first**\nExample:\n>nums = [-10,8,6,7,3,-2,-3]\nnums.sort() >> [-10,-3,-2,3,6,7,8]\nhence negative numbers in the left side and positive of the right\n\n**2) Took 2 points i and j**\n>i represents elements with negative indexes\nj represents elements with positive indexes\n\n**3) Find the sum of nums[i] and nums[j]**\n>**case:1** if sum is 0 means -x and x presents in the array, return x >>> ie here, nums[ j ]\n>> returned nums[ j ] will be the largest Positive Integer That Exists With Its Negative since the array is sorted\n\n>**case:2** if sum < 0 implies more negative numbers is there \n>>hence move negative pointer\n>> i += 1\n\n>**case:3** if sum > 0 implies more positive numbers is there \n>>hence move positive pointer\n>> j -= 1\n\n\n\n# Complexity\n- Time complexity:O(log(n))\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n```\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n i = 0\n j = len(nums)-1\n nums.sort()\n while i<j:\n res = nums[i]+nums[j]\n if res==0:\n return nums[j]\n elif res>0:\n j -= 1\n else:\n i += 1\n return -1\n \n```
3
0
['Python3']
0
largest-positive-integer-that-exists-with-its-negative
Swift solution
swift-solution-by-azm819-eg4q
Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n)\n Add your space complexity here, e.g. O(n) \n\n# Co
azm819
NORMAL
2024-05-02T06:41:34.901573+00:00
2024-05-02T06:41:34.901599+00:00
27
false
# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n func findMaxK(_ nums: [Int]) -> Int {\n var numSet = Set<Int>()\n var result = -1\n for num in nums {\n numSet.insert(num)\n if abs(num) > result && numSet.contains(-num) {\n result = abs(num)\n }\n }\n return result\n }\n}\n\n```
3
0
['Array', 'Hash Table', 'Swift']
0
largest-positive-integer-that-exists-with-its-negative
Two pointer Approach | No extra space
two-pointer-approach-no-extra-space-by-a-hhl9
Approach\n- Sort input array so that all negatives are in begin and positives are in end\n- Keep two pointers one for positive and one for negative integers\n-
anupsingh556
NORMAL
2024-05-02T05:19:48.152014+00:00
2024-05-02T05:19:48.152045+00:00
5
false
# Approach\n- Sort input array so that all negatives are in begin and positives are in end\n- Keep two pointers one for positive and one for negative integers\n- Move the pointer af number with absolute larger value to next one if they are equal return the value \n\n# Complexity\n- Time complexity:\nO(nlogn)\n- Space complexity:\nConstant space\n# Code\n```\nclass Solution {\npublic:\n int findMaxK(vector<int>& a) {\n sort(a.begin(), a.end());\n int s =0,e=a.size()-1;\n while(s<e&&a[s]<0&&a[e]>0) {\n if(a[s]==a[e]*-1)return a[e];\n if(a[s]*-1>a[e])s++;\n else e--;\n }\n return -1;\n }\n};\n```
3
0
['C++']
0
largest-positive-integer-that-exists-with-its-negative
C# Solution for Largest Positive Integer That Exists With Its Negative Problem
c-solution-for-largest-positive-integer-z5ua1
Intuition\n Describe your first thoughts on how to solve this problem. \nThe intuition behind this C# solution is to utilize two pointers starting from both end
Aman_Raj_Sinha
NORMAL
2024-05-02T04:54:46.257469+00:00
2024-05-02T04:54:46.257494+00:00
133
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind this C# solution is to utilize two pointers starting from both ends of the sorted array, moving towards each other to efficiently find pairs of numbers that sum up to zero.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1.\tSort the array to simplify the search process.\n2.\tInitialize two pointers, left starting from the beginning of the array, and right starting from the end.\n3.\tMove the pointers towards each other while checking the sum of the elements pointed by them.\n4.\tIf the sum is zero, it means we found a pair where one element is the negative of the other. Update maxK if necessary and move both pointers inward.\n5.\tIf the sum is negative, increment the left pointer to increase the sum.\n6.\tIf the sum is positive, decrement the right pointer to decrease the sum.\n7.\tReturn maxK or -1 if no such k exists\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\u2022\tSorting the array takes O(n log n) time.\n\u2022\tThe two-pointer approach traverses the array once, which has a time complexity of O(n).\n\u2022\tThus, the overall time complexity is O(n log n) due to sorting.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(1) because the solution only utilizes a constant amount of extra space for variables like maxK, left, and right, regardless of the size of the input array.\n\n# Code\n```\npublic class Solution {\n public int FindMaxK(int[] nums) {\n Array.Sort(nums);\n int maxK = -1;\n \n int left = 0, right = nums.Length - 1;\n while (left < right) {\n int sum = nums[left] + nums[right];\n if (sum == 0) {\n maxK = Math.Max(maxK, Math.Abs(nums[right]));\n left++;\n right--;\n } else if (sum < 0) {\n left++;\n } else {\n right--;\n }\n }\n \n return maxK;\n }\n}\n```
3
0
['C#']
0
largest-positive-integer-that-exists-with-its-negative
Maximum Absolute Value Pair in Sorted Array: Two Pointer Approach
maximum-absolute-value-pair-in-sorted-ar-9c7c
Intuition\n The problem likely involves finding some maximum value or satisfying certain conditions within an array. The use of sorting and two pointers suggest
samarp_1001
NORMAL
2024-05-02T04:53:05.849352+00:00
2024-05-02T04:53:05.849397+00:00
249
false
# Intuition\n The problem likely involves finding some maximum value or satisfying certain conditions within an array. The use of sorting and two pointers suggests there\'s a strategy involving comparing elements from both ends of the array.\n\n# Approach\nOne potential approach is to sort the array and then use two pointers, one starting from the beginning and the other from the end. By comparing the absolute values of elements at these pointers, we can gradually move towards the middle, adjusting the pointers based on the comparison.\n\n# Complexity\n- Time complexity:\n Sorting the array takes $$O(n \\log n)$$ time, where $$n$$ is the size of the array. The while loop iterates through the array once, which takes $$O(n)$$ time. Therefore, the overall time complexity is $$O(n \\log n)$$.\n\n- Space complexity:\n The space complexity is $$O(1)$$ since the algorithm uses only a constant amount of extra space, independent of the size of the input array. \n\n# Code\n```\nclass Solution {\npublic:\n int findMaxK(vector<int>& v) {\n sort(v.begin(),v.end());\n int i = 0;\n int j = v.size()-1;\n while(i < j)\n {\n if(v[i] == -v[j] || v[j] == -v[i] )\n return abs(v[i]);\n if(abs(v[i]) < abs(v[j]))\n {\n j--;\n }\n else \n i++;\n }\n return -1;\n\n }\n};\n```
3
0
['Two Pointers', 'Sorting', 'C++']
1
largest-positive-integer-that-exists-with-its-negative
Beats 99.07% Time⌛ 98.70% Memory 💾🔥🔥 | Python, C++ 💻 | Clear Explanation📗
beats-9907-time-9870-memory-python-c-cle-toeu
Beats 99.07% Time\u231B 98.70% Memory \uD83D\uDCBE\uD83D\uDD25\uD83D\uDD25 | Python, C++ \uD83D\uDCBB | Clear Explanation\uD83D\uDCD7\n## 1. Proof\n Describe yo
kcp_1410
NORMAL
2024-05-02T04:02:23.840951+00:00
2024-05-02T06:30:30.736973+00:00
103
false
# Beats 99.07% Time\u231B 98.70% Memory \uD83D\uDCBE\uD83D\uDD25\uD83D\uDD25 | Python, C++ \uD83D\uDCBB | Clear Explanation\uD83D\uDCD7\n## 1. Proof\n<!-- Describe your first thoughts on how to solve this problem. -->\n### 1.1. Python3\n![image.png](https://assets.leetcode.com/users/images/11bf8ec1-ba8b-418f-9ae2-4a5d23b5702c_1714622105.9590352.png)\n### 1.2. C++\n![image.png](https://assets.leetcode.com/users/images/4501ad22-9d9b-42cd-916c-b402ca4554e6_1714623094.1484709.png)\n\n## 2. Approach\n**Sorting** & **Two pointers**\n\n## 3. Code (with explanation each line)\n```python3 []\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int: # Two pointers\n nums.sort() # Negative integer with max abs value (|-|) on the left, whereas the max positive integer (+) on the right\n l, r = 0, len(nums) - 1 # left & right pointers -> We go from both ends to inside to get the max value\n \n while nums[l] < 0 and nums[r] > 0: # Ensure the left pointer always points to a negative integer (-) & right pointer always points to a positive integer (+)\n neg, pos = abs(nums[l]), nums[r] # Get the absolute value of negative number (-), and positive number (+) -> for easier comparison\n if neg == pos: # If abs of negative (|-|) matches positive (+) -> Found\n return pos # Return the positive (+) number\n elif neg < pos: # The positive number (+) is too large compared to the corresponding abs of negative number (|-|) which left pointer is pointing at\n r -= 1 # Get a smaller positive number (+) by moving right pointer inside\n else: # The abs of negative number (|-|) is too large compared to the corresponding positive number (+) which right pointer is pointing at\n l += 1 # Get a smaller abs of negative number (|-|) by moving left pointer inside\n \n return -1 # Not found\n```\n```cpp []\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n int l = 0, r = nums.size() - 1;\n\n while ((nums[l] < 0) && (nums[r] > 0)) {\n int neg = abs(nums[l]), pos = nums[r];\n if (neg == pos) {\n return pos;\n }\n else if (neg < pos) {\n r--;\n }\n else {\n l++;\n }\n }\n return -1;\n }\n};\n```\n## 4. Complexity\n- Time complexity: $$O((N*logN) + N/2)$$ simplified to $$O(N*logN)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n### Upvote if you find this solution helpful, thank you \uD83E\uDD0D
3
0
['Two Pointers', 'Sorting', 'C++', 'Python3']
0
largest-positive-integer-that-exists-with-its-negative
Easy JS code
easy-js-code-by-nbekweb-1ydg
\n\n# Code\n\nvar findMaxK = function(nums) {\n result = -1\n\n for (let i = 0; i < nums.length; i++) {\n if (nums.indexOf(-nums[i], i+1) > 0) \n
Nbekweb
NORMAL
2024-05-02T03:07:30.901639+00:00
2024-05-02T03:07:30.901662+00:00
593
false
\n\n# Code\n```\nvar findMaxK = function(nums) {\n result = -1\n\n for (let i = 0; i < nums.length; i++) {\n if (nums.indexOf(-nums[i], i+1) > 0) \n if (Math.abs(nums[i]) > result) result = Math.abs(nums[i]) \n }\n\n return result\n};\n```
3
0
['JavaScript']
2
largest-positive-integer-that-exists-with-its-negative
C++ One Pass Liner Solution | Beats 💯✅
c-one-pass-liner-solution-beats-by-shobh-kw1d
Intuition\n Describe your first thoughts on how to solve this problem. \nTo efficiently solve this problem, we employ a strategy that utilizes a vector seen to
shobhitkushwaha1406
NORMAL
2024-05-02T01:48:02.171200+00:00
2024-05-02T01:48:02.171222+00:00
11
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo efficiently solve this problem, we employ a strategy that utilizes a vector seen to keep track of encountered numbers. Initializing seen with a size of 1001, we anticipate integers ranging from 0 to 1000 inclusively within nums.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. We iterate through each integer x in the nums vector, obtaining its absolute value y using abs(x), and determine whether x is negative or positive.\n2. If x is negative, we update seen[y] using a binary OR operation (|) with 2. If x is positive, we update seen[y] using a binary OR operation with 1.\n3. Upon encountering a number y where seen[y] contains both 1 and 2 (indicating the presence of both -y and y in the vector), we update our maximum k value.\n4. Finally, we return the maximum k found during the iteration.\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n vector<int>seen(1001);\n int k=-1;\n for(int x:nums){\n int y=abs(x);\n if (x<0) seen[y]|=2;\n else seen[y]|=1;\n if (seen[y]==3) k=max(k, y);\n }\n return k;\n }\n};\n```
3
0
['Bit Manipulation', 'C++']
0
largest-positive-integer-that-exists-with-its-negative
C++ Simple Solution Using set and Priority_queue
c-simple-solution-using-set-and-priority-ynvt
Intuition\n Describe your first thoughts on how to solve this problem. \nIntuition for that problem is that find all unique element present in the array ,Now we
skill_improve
NORMAL
2024-05-02T01:10:46.107929+00:00
2024-05-02T01:10:46.107947+00:00
143
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIntuition for that problem is that find all unique element present in the array ,Now we want greatest element of which its negation exist then put all the positive element in the priority-queue and simply iterating the pq and checking .\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. We use a priority queue (pq) to keep track of positive integers in descending order.\nWe use a set (st) to keep track of all unique integers in the array.\n1. For each element i in nums, we insert i into the set and if i is greater than 0, we push it into the priority queue.\n1. We iterate through the priority queue. For each element x in the priority queue:\n - If the set contains -x, we return x as it satisfies the condition.\n- Otherwise, we pop the top element from the priority queue.\n4. If no such k is found, we return -1.\n\n# Complexity\n**Time complexity**:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n1. Let n be the size of the input array nums.\n1. Building the set and priority queue takes O(nlogn) time.\n1. The loop to check for the maximum k takes O(n) time in the worst case.\n1. Overall, the time complexity is O(nlogn).\n\n\n![upvote.png](https://assets.leetcode.com/users/images/2a16210b-be33-43ae-b22e-259595b7f631_1714612239.7901266.png)\n\n**Space complexity**:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n1. We use additional space for the priority queue and the set, both of which can store up to n elements.\n1. The space complexity is O(n).\n\n# Code\n```\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n priority_queue<int> pq;\n set<int> st;\n for(auto i:nums){\n st.insert(i);\n if(i>0) pq.push(i);\n }\n while(!pq.empty()){\n if(st.find(-pq.top())!=st.end()) return pq.top();\n else pq.pop();\n }\n return -1;\n }\n};\n```\nHappy Coding
3
0
['Array', 'Hash Table', 'Two Pointers', 'Sorting', 'C++']
1
largest-positive-integer-that-exists-with-its-negative
Two Pointer_Very simple_Python_C++
two-pointer_very-simple_python_c-by-saqu-1704
Intuition\n\npython []\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n nums.sort()\n l, r = 0, len(nums)-1\n \n
Saquif_Sohol
NORMAL
2024-05-02T01:05:34.599281+00:00
2024-05-02T01:05:34.599312+00:00
783
false
# Intuition\n\n```python []\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n nums.sort()\n l, r = 0, len(nums)-1\n \n while(nums[l]<0 and l<r):\n if nums[l]*(-1) == nums[r]:\n return nums[r]\n if nums[l]*(-1) > nums[r]:\n l += 1\n else:\n r -= 1\n \n return -1\n```\n```C++ []\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n int i=0;\n sort(nums.begin(), nums.end());\n\n int r = nums.size()-1;\n int l = 0;\n while(nums[l] < 0 && l<r){\n if(nums[l] == -nums[r])\n return nums[r];\n if(-nums[l] > nums[r])\n l++;\n else\n r--;\n }\n return -1;\n }\n};\n```\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nLet\'s understand with an example, \nnums = [-1, -2, -10, 3, 4, 2, 7]\nafter sorting the array,\nnums = [-10, -2, -1, 2, 3, 4, 7]\nfixed the left and right pointer :: left = 0, right = nums.size()-1\nnow iterate for left and right while(left < right)\n\nnums[left] = nums[0] = -10\nnums[right] = nums[6] = 7\nnums[left]*(-1) = -10*(-1) = 10\n**10 > 7** so make the **left++** [move the left pointer forward] cause it is not possible having the element 10 inside the array\n\nnow left = 1 and right remain same, right = 6\nnums[left]*(-1) = nums[1]*(-1) = 2\nnums[right] = nums[6] = 7\n**2 < 7** so make the **right--** [move the right pointer backward cause it is not possible having the element -7 inside the array]\n\nnow left remain same and right = 5 and so on.\nin this way the right will stop at the point 3\nthen, \n**nums[left] = nums[1] = -2\nnums[right] = nums[3] = 2\nnow nums[1]*-1 == nums[3]\n so return nums[3];**\n\n\nafter iterating while(left < right)\n if we don\'t get any same value like nums[left]*(-1) == nums[right]\nthen it is proved that there is no element exist like that.\nso **return -1**.\n\n\n\n# Complexity\n- Time complexity:\nO(n)\n\n\n# Please upvote it, if this solution has helped you at all. \n\n\n\n\n\n\n\n\n\n\n\n
3
0
['Two Pointers', 'C++', 'Python3']
6
largest-positive-integer-that-exists-with-its-negative
Easy Java Solution || Beginner Friendly
easy-java-solution-beginner-friendly-by-9f1t4
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
anikets101
NORMAL
2024-04-22T02:21:21.603581+00:00
2024-04-22T02:21:21.603613+00:00
188
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int findMaxK(int[] nums) {\n int n= nums.length;\n Arrays.sort(nums);\n for(int i=n-1; i>=0; i--)\n { \n for(int j=0; j<n; j++)\n {\n if(nums[i]==-nums[j])\n return (nums[i]);\n }\n }\n return -1;\n }\n}\n```
3
0
['Java']
0
largest-positive-integer-that-exists-with-its-negative
Beats 100% of users with C++|| Using Map and Two Pointer || Faster Solution || Easy to Understand ||
beats-100-of-users-with-c-using-map-and-qujx0
Abhiraj Pratap Singh\n\n---\n\n# if you like the approach please upvote it\n\n---\n\n# Intuition\n- The problem appears to involve finding the maximum value k s
abhirajpratapsingh
NORMAL
2023-12-20T19:31:08.017180+00:00
2024-05-02T17:06:16.044091+00:00
87
false
# Abhiraj Pratap Singh\n\n---\n\n# if you like the approach please upvote it\n\n---\n\n# Intuition\n- The problem appears to involve finding the maximum value k such that both k and -k exist in the given vector.\n\n---\n\n![1713037055032.png](https://assets.leetcode.com/users/images/22962e38-74c4-48c5-9c08-c40e4d8b9bef_1714669404.123081.png)\n\n\n---\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Use an ordered map to count the occurrences of each number in the vector.\n2. Iterate through the map:\n - For each element it, check if its negative counterpart -it exists in the map and it is positive.\n - If both it and -it exist, update the large variable to it.\n3. Return the maximum value found, which represents the maximum k such that both k and -k exist.\n4. If no such k is found, return -1.\n\n---\n\n# Complexity\n- **Time complexity :**\n - Constructing the map takes O(nlogn) time, where n is the number of elements in the vector.\n - Iterating through the map takes O(n) time.\n - Overall, the time complexity is O(nlogn).\n\n---\n\n- **Space complexity :**\n - We use O(n) extra space for the map.\n - Overall, the space complexity is O(n).\n\n---\n\n\n# Code\n```\nclass Solution {\npublic:\n // Using ordered Map\n int findMaxK(vector<int>& nums) \n {\n map<int,int>mp;\n int large=0;\n for(int i=0;i<nums.size();i++)\n mp[nums[i]]++;\n for(auto it : mp)\n {\n if(it.first>0)\n {\n if(mp[(it.first)*-1])\n large=it.first;\n }\n }\n if(large!=0)\n return large;\n return -1;\n }\n};\n```\n#code\n```\nclass Solution {\npublic:\n //Using Sorting then Two Pointer Appraoch\n int findMaxK(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n int i=0;\n int j=nums.size()-1;\n while(i<j){\n \n if(-nums[i]==nums[j]) return nums[j];\n else if(-nums[i]>nums[j]) i++;\n else j--;\n }\n return -1;\n }\n};\n```
3
0
['Hash Table', 'Two Pointers', 'Ordered Map', 'Sorting', 'C++']
1
largest-positive-integer-that-exists-with-its-negative
Simple Solution
simple-solution-by-adwxith-54lw
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
adwxith
NORMAL
2023-12-19T10:27:09.749697+00:00
2023-12-19T10:27:09.749729+00:00
139
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar findMaxK = function(nums) {\n res=-1\n let seen=new Set()\n for(const num of nums){\n if(seen.has(-num)){\n res=Math.max(res,Math.abs(num))\n }\n seen.add(num)\n }\n \n return res\n \n};\n```
3
0
['JavaScript']
1
largest-positive-integer-that-exists-with-its-negative
100% - O(N) - O(1) Java✅
100-on-o1-java-by-omjethva24-2x2s
Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(1)\n Add your space complexity here, e.g. O(n) \n\n# Co
omjethva24
NORMAL
2023-11-16T07:47:21.817753+00:00
2023-11-16T07:47:21.817781+00:00
121
false
# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int findMaxK(int[] nums) {\n int[] freq = new int[1001];\n\n for(int num : nums){\n if(num<0) freq[num*-1]++;\n };\n\n int max = -1;\n\n for(int num : nums){\n if(num > 0){\n if(freq[num]!=0){\n if(num > max) max = num;\n }\n }\n }\n\n return max;\n }\n}\n```\n![upvote.jpeg](https://assets.leetcode.com/users/images/c1ea0dda-2ba4-4fd1-9874-017385b54bbc_1700120804.091342.jpeg)\n\n
3
0
['Java']
2
largest-positive-integer-that-exists-with-its-negative
Beginner-friendly || Simple solution with HashMap
beginner-friendly-simple-solution-with-h-f455
Intuition\nLet\'s briefly explain, what problem is:\n- there\'s a list of nums\n- our goal is to find the maximum, that has a negative integer of himself (i.e.,
subscriber6436
NORMAL
2023-10-25T21:07:13.358601+00:00
2023-10-25T21:08:31.385017+00:00
221
false
# Intuition\nLet\'s briefly explain, what problem is:\n- there\'s a list of `nums`\n- our goal is to find **the maximum**, that has a **negative integer of himself** (i.e., 2 and -2 etc)\n\nThe approach is **straighforward**: iterate over `nums` and at each step check, if a particular integer is **a maximum one**, and find it **negative version of himself**.\n\nIf this integer **doesn\'t exist**, simply return `-1`.\n\n# Approach\n1. declare `set` for effective indexing of a **negative version of a current maximum**\n2. declare `ans = -1`\n3. iterate over `nums` and **find a maximum**\n4. return `ans`\n\n# Complexity\n- Time complexity: **O(N)**, for building a set and iterating over `nums`\n\n- Space complexity: **O(N)**, the same for storing `set`.\n\n# Code in Python3\n```\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n cache = set(nums)\n ans = -1\n\n for num in nums:\n if -num in cache and num > ans: ans = num\n \n return ans\n```\n# Code in TypeScript\n```\nfunction findMaxK(nums: number[]): number {\n const cache = new Set(nums)\n let ans = -1\n\n for (let i = 0; i < nums.length; i++) {\n const curMax = nums[i]\n\n if (cache.has(-curMax) && curMax > ans) ans = curMax\n }\n\n return ans\n};\n```
3
0
['Array', 'Hash Table', 'TypeScript', 'Python3']
1
largest-positive-integer-that-exists-with-its-negative
Python3: solution beats 99.89%
python3-solution-beats-9989-by-resilient-9gqf
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
ResilientWarrior
NORMAL
2023-08-27T13:18:34.392179+00:00
2023-08-27T13:18:34.392208+00:00
6
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n nums.append(0)\n nums.sort()\n coma = nums.index(0)\n neg = nums[:coma]\n pos = nums[coma+1:][::-1]\n neg = set(neg)\n for i in pos:\n if -i in neg:\n return i\n return -1\n\n```
3
0
['Python3']
0
largest-positive-integer-that-exists-with-its-negative
Easy to understand C++ Solution using set SC:O(n) ✅✅
easy-to-understand-c-solution-using-set-z5b4q
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nI used the set to store the numbers in sorted order.\n\n# Complexity\n- T
om_limbhare
NORMAL
2023-01-20T16:39:55.882652+00:00
2023-02-17T09:02:19.222324+00:00
338
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nI used the set to store the numbers in sorted order.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n set <int> s;\n for(int i:nums) s.insert(i);\n int mini=INT_MIN;\n for(auto it:s){\n if(it<0){\n if(s.find(abs(it))!=s.end()){\n mini=max(abs(it),mini);\n }\n }\n }\n if(mini!=INT_MIN)\n return mini;\n else return -1;\n }\n};\n```
3
0
['Array', 'C++']
3
largest-positive-integer-that-exists-with-its-negative
python, sort(), double pointers
python-sort-double-pointers-by-nov05-bmwg
ERROR: type should be string, got "https://leetcode.com/submissions/detail/854012683/\\n\\nRuntime: 126 ms, faster than 98.12% of Python3 online submissions for Largest Positive Integer That Exists"
nov05
NORMAL
2022-12-03T18:05:42.768024+00:00
2022-12-03T18:11:50.777103+00:00
373
false
ERROR: type should be string, got "https://leetcode.com/submissions/detail/854012683/\\n```\\nRuntime: 126 ms, faster than 98.12% of Python3 online submissions for Largest Positive Integer That Exists With Its Negative.\\nMemory Usage: 14.1 MB, less than 90.76% of Python3 online submissions for Largest Positive Integer That Exists With Its Negative.\\n```\\n```\\nclass Solution:\\n def findMaxK(self, nums: List[int]) -> int:\\n nums.sort()\\n l = len(nums)\\n i, j = 0, l-1\\n while i<l and j>=0:\\n if -nums[i]==nums[j]:\\n return nums[j]\\n elif -nums[i]<nums[j]:\\n j-=1\\n else:\\n i+=1\\n return -1\\n```"
3
0
['Sorting', 'Python']
0
largest-positive-integer-that-exists-with-its-negative
Simple C++ solution | O(n) |2 pointer simple approach
simple-c-solution-on-2-pointer-simple-ap-rg11
```\nclass Solution {\npublic:\n int findMaxK(vector& nums) {\n sort(nums.begin(),nums.end());\n int s=0,e=nums.size()-1;\n while(s<e){\
mohiteravi348
NORMAL
2022-11-27T18:37:14.767847+00:00
2022-11-27T18:37:14.767978+00:00
73
false
```\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n int s=0,e=nums.size()-1;\n while(s<e){\n if(nums[s]+nums[e]==0)\n return nums[e];\n else if(nums[s]+nums[e]<0)s++;\n else\n e--;\n }\n return -1;\n }\n};
3
0
['C']
0
largest-positive-integer-that-exists-with-its-negative
Easy Python Solution
easy-python-solution-by-vistrit-0d1x
Code\n\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n nums.sort()\n for i in nums[::-1]:\n if -i in nums:\n
vistrit
NORMAL
2022-11-03T15:42:43.959770+00:00
2022-11-03T15:42:43.959809+00:00
683
false
# Code\n```\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n nums.sort()\n for i in nums[::-1]:\n if -i in nums:\n return i\n return -1\n```
3
0
['Python', 'Python3']
3
largest-positive-integer-that-exists-with-its-negative
[JAVA] easiest two pointer solution
java-easiest-two-pointer-solution-by-jug-bgeh
\n\n# Code\n\nclass Solution {\n public int findMaxK(int[] nums) {\n Arrays.sort(nums);\n for(int i = 0; i < nums.length; i ++) {\n for(in
Jugantar2020
NORMAL
2022-10-24T16:48:31.082466+00:00
2022-10-24T16:48:31.082511+00:00
254
false
\n\n# Code\n```\nclass Solution {\n public int findMaxK(int[] nums) {\n Arrays.sort(nums);\n for(int i = 0; i < nums.length; i ++) {\n for(int j = nums.length - 1; j > 0; j --) \n if(nums[i] + nums[j] == 0) return nums[j];\n } \n return - 1;\n }\n}\n```\n# PLEASE UPVOTE IF IT WAS HELPFULL
3
0
['Java']
3
largest-positive-integer-that-exists-with-its-negative
Two sum||C++||Java ||4 lines solution||Sorting
two-sumcjava-4-lines-solutionsorting-by-1p4hm
\n\n# Code\nJAVA solution \n\nclass Solution {\n public int findMaxK(int[] nums) {\n Arrays.sort(nums);\n for(int i=0;i<nums.length;i++)\n
Kashif_Rahman
NORMAL
2022-10-18T20:26:06.755605+00:00
2022-10-18T20:26:06.755644+00:00
151
false
\n\n# Code\nJAVA solution \n```\nclass Solution {\n public int findMaxK(int[] nums) {\n Arrays.sort(nums);\n for(int i=0;i<nums.length;i++)\n for(int j=nums.length-1;j>=0;j--)\n if(nums[i]+nums[j]==0) return nums[j];\n return -1;\n }\n}\n```\nC++ solution \n```\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n for(int i=0;i<nums.size();i++)\n for(int j=nums.size()-1;j>=0;j--)\n if(nums[i]+nums[j]==0) return nums[j];\n return -1;\n }\n};\n```
3
0
['Sorting', 'C++', 'Java']
1
largest-positive-integer-that-exists-with-its-negative
Java | hashset | easy to understand
java-hashset-easy-to-understand-by-conch-vyob
\n //Runtime: 5 ms, faster than 100.00% of Java online submissions for Largest Positive Integer That Exists With Its Negative.\n //Memory Usage: 42.5 MB,
conchwu
NORMAL
2022-10-16T05:54:26.321099+00:00
2022-10-16T06:07:15.062284+00:00
453
false
```\n //Runtime: 5 ms, faster than 100.00% of Java online submissions for Largest Positive Integer That Exists With Its Negative.\n //Memory Usage: 42.5 MB, less than 60.00% of Java online submissions for Largest Positive Integer That Exists With Its Negative.\n\t//Time: O(N); Space: O(N)\n public int findMaxK(int[] nums) {\n\n Set<Integer> set = new HashSet<>();\n for (int i = 0; i < nums.length; i++)\n //if (nums[i] < 0)\n set.add(nums[i]);\n\n int res = -1;\n for (int i = 0; i < nums.length; i++) {\n if (nums[i] > res && set.contains(-nums[i]))\n res = nums[i];\n }\n return res;\n }\n\n```
3
0
['Ordered Set', 'Java']
2
largest-positive-integer-that-exists-with-its-negative
Binary Search O(NlogN) Solution
binary-search-onlogn-solution-by-travanj-vkin
cpp\nclass Solution {\npublic:\n int findMaxK(vector<int> &nums) {\n int n = nums.size();\n sort(nums.begin(), nums.end());\n for (int i
travanj05
NORMAL
2022-10-16T04:44:04.151173+00:00
2022-10-16T04:44:04.151196+00:00
108
false
```cpp\nclass Solution {\npublic:\n int findMaxK(vector<int> &nums) {\n int n = nums.size();\n sort(nums.begin(), nums.end());\n for (int i = n - 1; i >= 0; i--) {\n if (nums[i] < 0) return -1;\n if (binary_search(nums.begin(), nums.end(), -nums[i])) {\n return nums[i];\n }\n }\n return -1;\n }\n};\n```\n\nTime Complexity: **O(N * logN)**\nSpace Complexity: **O(1)**\n
3
0
['C', 'Binary Tree', 'C++']
1
largest-positive-integer-that-exists-with-its-negative
✅C++||✅Intuitive HashMap ||✅Short Code
cintuitive-hashmap-short-code-by-bhushan-tkwk
\nint findMaxK(vector<int>& nums) {\n \n map<int,int> mp ;\n for( auto it : nums ) mp[it]++;\n \n int ans = INT_MIN ;\n
Bhushan_Mahajan
NORMAL
2022-10-16T04:06:18.218289+00:00
2022-10-16T04:06:45.355175+00:00
1,874
false
```\nint findMaxK(vector<int>& nums) {\n \n map<int,int> mp ;\n for( auto it : nums ) mp[it]++;\n \n int ans = INT_MIN ;\n bool gotAnsr = false ;\n \n for( int i=0 ; i<nums.size() ; i++ ){\n \n if( nums[i] > 0 ) {\n if( mp.find( 0-nums[i] ) != mp.end() ){\n \n ans = max( ans, nums[i] );\n gotAnsr = true ;\n }\n }\n }\n \n if( gotAnsr ) return ans ;\n return -1 ;\n }\n```
3
0
[]
1
largest-positive-integer-that-exists-with-its-negative
C++ Array
c-array-by-theomkumar-vwew
Bruteforce Approach \n\n int findMaxK(vector<int>& nums) {\n int maxi = -1;\n for (int i = 0; i < nums.size(); i++)\n {\n for (i
theomkumar
NORMAL
2022-10-16T04:04:51.296446+00:00
2022-10-16T04:18:33.480770+00:00
295
false
Bruteforce Approach \n```\n int findMaxK(vector<int>& nums) {\n int maxi = -1;\n for (int i = 0; i < nums.size(); i++)\n {\n for (int j = 0; j < nums.size(); j++)\n {\n if (nums[i] == nums[j]*-1)\n maxi = max(nums[i], maxi);\n }\n }\n return maxi;\n }\n```
3
0
['C', 'C++']
1
largest-positive-integer-that-exists-with-its-negative
✅C++|| Simple Brute Force|| Easy Solution
c-simple-brute-force-easy-solution-by-in-i47b
\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n int n = nums.size();\n int sum = 0;\n
indresh149
NORMAL
2022-10-16T04:03:32.024219+00:00
2022-10-16T04:03:32.024245+00:00
456
false
```\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n int n = nums.size();\n int sum = 0;\n int maxi = -1;\n for(int i=0;i<n;i++){\n int a = nums[i]; \n for(int j=i+1;j<n;j++){\n if(a+nums[j] == 0){\n sum = nums[j];\n if(nums[j] > maxi ){\n maxi = nums[j];\n }\n }\n }\n }\n if(maxi > 0){\n return maxi;\n }\n return -1;\n }\n};\n```\n**Please upvote if it was helpful for you, thank you!**
3
0
['C']
0
largest-positive-integer-that-exists-with-its-negative
Easy to Understand | C++
easy-to-understand-c-by-s1ddharth-53aa
\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n map<int, set<int>> mp;\n for(auto &it: nums) {\n mp[abs(it)].inser
s1ddharth
NORMAL
2022-10-16T04:03:20.489699+00:00
2022-10-16T04:03:20.489747+00:00
1,730
false
```\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n map<int, set<int>> mp;\n for(auto &it: nums) {\n mp[abs(it)].insert(it);\n }\n int maxi = INT_MIN;\n \n for(auto &it: mp) {\n if(it.second.size() == 2) {\n maxi = max(it.first, maxi);\n }\n }\n return maxi == INT_MIN ? -1 : maxi;\n }\n};\n```\n\n
3
0
['C']
1
largest-positive-integer-that-exists-with-its-negative
simplest two pointer, explained
simplest-two-pointer-explained-by-pitche-mtkm
Intuitionwe need to find the sum of a negative number and a positive number to be 0we sort our array, initialize left as zero and right as final indexwe basical
pitcherpunchst
NORMAL
2024-12-20T13:09:37.015698+00:00
2024-12-20T13:09:37.015698+00:00
54
false
# Intuition we need to find the sum of a negative number and a positive number to be 0 we sort our array, initialize left as zero and right as final index we basically divide the array into negative and positive half, left pointer starts from the most negative element to the least negative right pointer starts from the most positive element to the least positive we run our while loop as long as left pointer points to a negative number and right pointer to a positive number we define a sum, which is sum of negative and positive number i) if sum is positive, that means our positive number is too big, so we check the next most positive number ii) if sum is negative, that means our negative number is too negative, so we check the next most negative number iii) if sum is 0, we have our answer if we did not get an answer we return -1; # Complexity - Time complexity: O(nlogn) - Space complexity: O(1) # Code ```cpp [] class Solution { public: int findMaxK(vector<int>& nums) { sort(nums.begin(),nums.end()); int left = 0,right=nums.size()-1; while(nums[left]<0 && nums[right]>0) { int sum = nums[left] + nums[right]; if(sum>0) right--; if(sum<0) left++; if(sum==0) return nums[right]; } return -1; } }; ```
2
0
['C++']
0
largest-positive-integer-that-exists-with-its-negative
Easy Solution using C++ for Beginners using For Loop
easy-solution-using-c-for-beginners-usin-f1tp
Intuition\nReturn the value if the maximum positive element has its negative value in the array\n Describe your first thoughts on how to solve this problem. \n\
Viggu_Vignesh
NORMAL
2024-09-24T08:13:56.764090+00:00
2024-09-24T08:13:56.764109+00:00
3
false
# Intuition\nReturn the value if the maximum positive element has its negative value in the array\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n# Sort the array\n\n**Use 2 for loops**\n\n- 1st loop iterates from first element to last(small to big)\n\n- 2nd loop iterates from last element to first(big to small)\n\n*By multiplying the 1st loop with -1, check if the 1st loop\'s value is equal to the 2nd loop which begins from larger value, if true return the 2nd loop\'s value, else return -1.*\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: 69.74%\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: 67.83%\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n int n=nums.size();\n sort(nums.begin(),nums.end());\n for(int i=0;i<n;i++)\n {\n for(int j=n-1;j>=0;j--)\n {\n if(nums[j]==(nums[i]*(-1)))\n return nums[j];\n }\n }\n return -1;\n }\n};\n```
2
0
['C++']
0
largest-positive-integer-that-exists-with-its-negative
use toSet()
use-toset-by-linhna3-g13s
\n# Code\n\nclass Solution {\n fun findMaxK(nums: IntArray): Int {\n val numsSet = nums.toSet()\n var result = -1\n for (num in nums) {\n if
LinhNA3
NORMAL
2024-05-03T10:57:25.561098+00:00
2024-05-03T10:57:25.561149+00:00
4
false
\n# Code\n```\nclass Solution {\n fun findMaxK(nums: IntArray): Int {\n val numsSet = nums.toSet()\n var result = -1\n for (num in nums) {\n if (-num in numsSet && num > result) {\n result = num\n }\n }\n return result\n }\n}\n```
2
0
['Kotlin']
0
largest-positive-integer-that-exists-with-its-negative
Simple Solution (Faster 100% Runtime) ✅
simple-solution-faster-100-runtime-by-pr-xh6l
\n# Approach\n- Reduce the entire inputArray into unique elements using Sets\n- Split the elements into two subarrays; positiveNums and negativeNums (absolutive
ProbablyLost
NORMAL
2024-05-02T13:26:02.486450+00:00
2024-05-02T14:13:19.589152+00:00
67
false
\n# Approach\n- Reduce the entire inputArray into unique elements using `Sets`\n- Split the elements into two **subarrays**; `positiveNums` and `negativeNums` (absolutive value)\n- Get the largest **intersection** (common element) between the two subarrays, if none exists, return `-1`\n\n# Code\n```\nclass Solution {\n func findMaxK(_ nums: [Int]) -> Int {\n let nums = Set(nums)\n var positiveNums = [Int]()\n var negativeNums = [Int]()\n \n for num in nums {\n if num > 0 {\n positiveNums.append(num)\n } else {\n negativeNums.append(abs(num))\n }\n }\n \n return largestIntersectionK(positiveNums, negativeNums)\n }\n \n private func largestIntersectionK(_ positiveNums: [Int], _ negativeNums: [Int]) -> Int {\n let positiveSet = Set(positiveNums)\n let negativeSet = Set(negativeNums)\n let intersectionArray = positiveSet.intersection(negativeSet)\n \n return intersectionArray.max() ?? -1\n }\n}\n```
2
0
['Array', 'Swift', 'Sorting']
0
largest-positive-integer-that-exists-with-its-negative
✅Easiest Solution🔥||O(N)🔥||Beginner Friendly✅🔥
easiest-solutiononbeginner-friendly-by-s-ctut
Intuition\n\n - The code uses a HashSet named hs to store unique values from the input array nums. This ensures that we only consider each value once, avoidin
siddhesh11p
NORMAL
2024-05-02T13:16:48.490333+00:00
2024-05-02T13:16:48.490385+00:00
49
false
# Intuition\n\n - The code uses a `HashSet` named `hs` to store unique values from the input array `nums`. This ensures that we only consider each value once, avoiding duplicate checks.\n - It then iterates through each value `valu` in the `HashSet`.\n - For each `valu`, it checks if its negation `-valu` exists in the `HashSet`. If it does, it updates the maximum value `max` if `valu` is greater than the current `max`.\n - Finally, it returns the maximum value `max` satisfying the condition.\n\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution {\n public int findMaxK(int[] nums) {\n\n HashSet <Integer> hs= new HashSet<>();\n\n for(int num : nums)\n {\n hs.add(num);\n }\n\n int max = -1;\n\n for(int valu : hs)\n {\n if(hs.contains(valu*-1))\n {\n if(max<valu)\n max=valu;\n }\n }\n\n return max;\n }\n}\n```
2
0
['Array', 'Hash Table', 'Two Pointers', 'Sorting', 'Java']
2
largest-positive-integer-that-exists-with-its-negative
This solution is even more straight then you.
this-solution-is-even-more-straight-then-yad3
Intuition\n Describe your first thoughts on how to solve this problem. \nHEY GUYS PLS UPVOTE PPL.\n# Approach\n Describe your approach to solving the problem. \
Abhishekkant135
NORMAL
2024-05-02T12:48:32.823956+00:00
2024-05-02T12:48:32.823974+00:00
119
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nHEY GUYS PLS UPVOTE PPL.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n\n1. **Initializing Variables:**\n - `HashSet<Integer> hm = new HashSet<>()`: Creates a HashSet named `hm` to store the unique numbers encountered while iterating through the `nums` array.\n - `int ans = -1`: Initializes a variable `ans` to store the maximum absolute difference found so far. It\'s initially set to -1 to indicate no such difference has been found yet.\n\n2. **Iterating Through the Array:**\n - The `for` loop iterates through each element (`nums[i]`) in the `nums` array.\n\n3. **Adding to HashSet and Checking for Negative Counterpart:**\n - `hm.add(nums[i])`: Attempts to add the current element (`nums[i]`) to the `HashSet` `hm`. If it\'s a new element, it gets added, and the method returns `true`.\n - `if (hm.contains(-nums[i]))`: Checks if the negative of the current element (`-nums[i]`) already exists in the `HashSet` `hm`.\n - If `hm.contains(-nums[i])` returns `true`, it means both the number and its negative counterpart have been encountered in the array. This signifies a potential absolute difference.\n\n4. **Updating Maximum Difference:**\n - `ans = Math.max(ans, Math.abs(nums[i]))`:\n - This line calculates the absolute value (positive distance from zero) of the current element `nums[i]` using `Math.abs(nums[i])`.\n - It then uses the `Math.max` function to compare this absolute value with the previously found `ans` (maximum difference).\n - The larger value between the current absolute value and `ans` is stored back in `ans`. This ensures `ans` always holds the maximum absolute difference found so far.\n\n5. **Returning the Result:**\n - `return ans`: After iterating through the entire array, `ans` will hold the maximum absolute difference (or -1 if no such difference exists). The code returns this value.\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n# Code\n```\nclass Solution {\n public int findMaxK(int[] nums) {\n HashSet<Integer> hm=new HashSet<>();\n int ans=-1;\n for(int i=0;i<nums.length;i++){\n hm.add(nums[i]);\n if(hm.contains(-nums[i])){\n ans=Math.max(ans,Math.abs(nums[i]));\n }\n }\n return ans;\n \n }\n}\n```
2
0
['Hash Table', 'Java']
0
largest-positive-integer-that-exists-with-its-negative
Java Solution 🖥️ 4ms 💯Beats 91.11% 🏃🏼💨💨💨
java-solution-4ms-beats-9111-by-purushar-vx1n
Intuition\n Describe your first thoughts on how to solve this problem. \nWe want to find the largest positive integer k such that -k also exists in the array.\n
purusharthcodeshere
NORMAL
2024-05-02T10:23:01.493104+00:00
2024-05-02T11:34:22.066474+00:00
25
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe want to find the largest positive integer `k` such that `-k` also exists in the array.\nNow there are two ways two search for such an integer `k`:\n\n# **Brute Force Method:**\n \nBrute force method is usually the simplest approach that we can come up for the solution and that is almost always doing exactly what the question asks. Since we want to find an integer `k` and its `additive inverse\xB9`, `-k` we can run two `for` loops to find such a number. We will run one `outer loop` to keep track of the maximum number at any particular instance and then run an `inner loop` to keep track of the `additive inverse\xB9` for the number at `i-th index`. This way we are keeping track of the maximum integer at every iteration and if its `additive inverse\xB9` exists in the array `nums` then we are storing it.\n \n```java []\nN = nums.length;\nint max = Integer.MIN_VALUE;\nint ans = Integer.MIN_VALUE;\n\nfor (int i = 0; i < N; i++) {\n max = Math.max(max, nums[i]) {\n\n for (int j = 0; j < N; j++) {\n int temp = nums[j] * -1;\n if (temp == max) {\n ans = Math.max(ans, max);\n }\n }\n}\n\nreturn ans;\n```\n\nThe **time complexity** of this approach is $$O(N^2)$$ as we iterate through the array eveytime for the number at `i-th index`. The Space Complexity is $$O(1)$$. Now the question arrises whether we can improve the efficiency of our code.\n\n**We can improve the Time Complexity with just two steps:**\n- Sorting The Array\n- Two Pointer Approach\n\n**Note:**\n\xB9 **Additive Inverse** of any integer is its negative counter part. Additive Inverse of `a` is `-a` and similarly additive inverse of `-a` is `a`. It is important to remember, to check whether two numbers are each other\'s `additve inverse\xB9`, we multiply one of them with `-1` instead of simply taking their absolute values. For example if `x = 1` and `y = 1`, then while their absolute values are equal, `x` and `y` are not each other\'s additive inverse.\n\n# Efficent Approach: Sorting with Two Pointers Approach\n<!-- Describe your approach to solving the problem. -->\n\nFirst we can sort the array and then take two pointers for the `first` and the `last` index.\n\n```\nArrays.sort(nums);\nint N = nums.length;\nint i = 0, j = N - 1;\n``` \n\nThen we run a while loop where we ensure that the `i-th` index is always smaller than the `j-th` index.\n\n```\nwhile (i < j) {\n //Logic\n //Some operations\n}\n```\n\nThen we access the values at the `i-th` and the `j-th` index and check if they are each other\'s `additive inverse\xB9` or not. If they are, then we can directly return the value at the `j-th index`. As we start from the last index of the sorted array and have found our `k-th` number, we do not need to go any further.\n\n while (i < j) {\n int start = nums[i];\n int end = nums[j];\n\n if ((start * -1) == end) {\n return end;\n } else if (/some other condition/) {\n /Some other operation/\n } else if (/another condition/) {\n /another operation/\n }\n }\n\nIf, however, we have not found our `k-th` number, then we have to increment or decrement out pointers depending upon the result. If the number `additive inverse\xB9` of the `start` was greater than `end` then that means we have found a smaller negative number than we desire and we increment our `i-th index` to the right.\n\nHowever, if we found that `end` was greater than the `additive inverse` of `start` then that means the highest possiblity of `k-th` number is yet to be found and we move our `j-th index` to the left.\n\nIf, at last, we are unable to find any such `k-th` number we return `-1`\n\n# Complexity\n- Time complexity: $$O(N*log N + N)$$ `(Linearithmic TC)`\n$$(N * log N)$$ `(Logarithmic TC)`for sorting and $$O(N)$$ `(Linear TC)` for the two pointer approach. However, since `Linearithmic TC` has superseding value than `Linear TC` so over all $$O(N*log N)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$ since there is no additional space used.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int findMaxK(int[] nums) {\n\n Arrays.sort(nums);\n int N = nums.length;\n int i = 0, j = N - 1;\n\n while (i < j) {\n int start = nums[i];\n int end = nums[j];\n\n if ((start * -1) == end) {\n return end;\n } else if ((start * -1) < end) {\n j--;\n } else if ((start * -1) > end) {\n i++;\n }\n }\n\n return -1;\n }\n}\n```
2
0
['Two Pointers', 'Sorting', 'Java']
0
largest-positive-integer-that-exists-with-its-negative
Kotlin. Beats 100% (205 ms). Bit masks solution.
kotlin-beats-100-205-ms-bit-masks-soluti-fq5l
\n\n# Code\n\nclass Solution {\n fun findMaxK(nums: IntArray): Int {\n val counters = IntArray(1024)\n var max = -1\n for (n in nums) {\
mobdev778
NORMAL
2024-05-02T06:39:09.979665+00:00
2024-05-02T06:45:08.287910+00:00
49
false
![image.png](https://assets.leetcode.com/users/images/eb45bdb1-1cc2-4185-b849-a92fcd93d202_1714631913.012272.png)\n\n# Code\n```\nclass Solution {\n fun findMaxK(nums: IntArray): Int {\n val counters = IntArray(1024)\n var max = -1\n for (n in nums) {\n val an = Math.abs(n)\n counters[an] = counters[an] or if (n < 0) 1 else 2\n if (counters[an] == 3) {\n max = Math.max(max, an)\n }\n }\n return max\n }\n}\n```\n\n# Alternative approach\n\nSolution with two boolean arrays is also possible.\n\n![image.png](https://assets.leetcode.com/users/images/44400810-eb7e-4850-bb48-17c35e765c5f_1714632170.7192981.png)\n\n```\nclass Solution {\n fun findMaxK(nums: IntArray): Int {\n val neg = BooleanArray(1024)\n val pos = BooleanArray(1024)\n var max = -1\n for (n in nums) {\n val an = Math.abs(n)\n if (n < 0) {\n if (pos[an]) max = Math.max(max, an) else neg[an] = true\n } else {\n if (neg[an]) max = Math.max(max, an) else pos[an] = true\n }\n }\n return max\n }\n}\n```\n
2
0
['Kotlin']
1
largest-positive-integer-that-exists-with-its-negative
✅Simple Two Pointer Approach O(N/2) Solution ✅
simple-two-pointer-approach-on2-solution-gbun
Intuition\nSum of the positive and negative of the same number is eaual to 0.\n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n-
abhay0007
NORMAL
2024-05-02T06:02:56.550859+00:00
2024-05-02T06:02:56.550897+00:00
1
false
# Intuition\nSum of the positive and negative of the same number is eaual to 0.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(N/2)\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n int i=0,j=nums.size()-1;\n while(i<j){\n int temp=nums[i]+nums[j];\n\n if(temp>0)\n j--;\n else if(temp<0)\n i++;\n else \n return nums[j];\n }\n return -1;\n }\n};\n```
2
0
['Array', 'Two Pointers', 'Sorting', 'C++']
0
largest-positive-integer-that-exists-with-its-negative
Beated 💯% | JAVA | 💪🏻🤟🏻
beated-java-by-anubhavkumar19-owgb
Intuition\n Describe your first thoughts on how to solve this problem. \nWe can two pointer aproach to find the desired result.\n\n# Approach\n Describe your ap
anubhavkumar19
NORMAL
2024-05-02T05:24:15.875872+00:00
2024-05-02T05:24:15.875904+00:00
78
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can two pointer aproach to find the desired result.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n> First, I\'ve sorted the **nums**. Then iterated through the **nums** using two pointers ***i*** and ***j***. ***i*** is moving from start to end and j is moving from end to start of **nums**. Compare **nums[i]*(-1)** and **nums[j]**, if equal the we have got the largest desired number as nums[j] else if **nums[j]** is lesser then **i++** else **j--**.\n\nAt the end return -1 if we have not got the result from **for** loop.\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int findMaxK(int[] nums) {\n Arrays.sort(nums);\n for(int i=0, j=nums.length-1; i<nums.length-1 && j>=0; ){\n if(nums[i]*(-1) == nums[j]) return nums[j];\n else if(nums[i]*(-1) > nums[j]) i++;\n else j--;\n }\n\n return -1;\n }\n}\n```
2
0
['Java']
1
largest-positive-integer-that-exists-with-its-negative
Easy Approach !
easy-approach-by-jasijasu959-kzy2
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
jasijasu959
NORMAL
2024-05-02T05:17:20.569263+00:00
2024-05-02T05:17:20.569297+00:00
25
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n int findMaxK(List<int> nums) {\n nums.sort();\n for(int i=nums.length-1 ; i>=0 ; i--){\n if(nums[i]>0 && nums.contains(-nums[i])){\n return nums[i]; \n }else if(nums[i]<0){\n return -1;\n }\n }\n return -1;\n }\n}\n```
2
0
['Dart']
0
largest-positive-integer-that-exists-with-its-negative
JS Easy One Line Solution
js-easy-one-line-solution-by-charnavoki-r8nm
\nvar findMaxK = nums => Math.max(...nums.filter(v => nums.includes(-v)), -1);\n
charnavoki
NORMAL
2024-05-02T05:07:13.277674+00:00
2024-05-02T05:25:12.803153+00:00
21
false
```\nvar findMaxK = nums => Math.max(...nums.filter(v => nums.includes(-v)), -1);\n```
2
0
['JavaScript']
0
largest-positive-integer-that-exists-with-its-negative
Solve without sort and in one linear loop
solve-without-sort-and-in-one-linear-loo-fz55
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nWe need to use a HashSet for storage and check each array element for the
raydensd
NORMAL
2024-05-02T04:49:33.074356+00:00
2024-05-02T05:01:35.854542+00:00
104
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nWe need to use a HashSet for storage and check each array element for the opposite sign in the HashSet.\n\n# Complexity\n- Time complexity:\n $$O(n)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\npublic class Solution {\n public int FindMaxK(int[] nums) {\n int mx = 0;\n int num = 0;\n HashSet<int> hset = new HashSet<int>();\n\n foreach(int n in nums)\n {\n num = Math.Abs(n);\n\n if(hset.Contains(n*-1))\n mx = Math.Max(mx,num);\n else if(!hset.Contains(n))\n hset.Add(n);\n }\n\n return mx==0?-1:mx;\n }\n}\n```
2
0
['C#']
0
largest-positive-integer-that-exists-with-its-negative
best approach JS
best-approach-js-by-javad_pk-gbrv
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
javad_pk
NORMAL
2024-05-02T04:35:13.269779+00:00
2024-05-02T04:35:13.269810+00:00
217
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar findMaxK = function(nums) {\n let obj={}\n nums.forEach(x=>obj[x]=1)\n let res=-1\n nums.forEach(x=>{\n if(obj[-x] && x>res) res=x\n })\n return res\n};\n```
2
0
['JavaScript']
0
largest-positive-integer-that-exists-with-its-negative
Single Pass Using Hash Set | Python
single-pass-using-hash-set-python-by-pra-0l9z
Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\n\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n seen = se
pragya_2305
NORMAL
2024-05-02T03:52:23.260449+00:00
2024-05-02T03:52:23.260502+00:00
228
false
# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n seen = set()\n ans = -float(\'inf\')\n\n for num in nums:\n if abs(num)>ans and -num in seen:\n ans = abs(num)\n seen.add(num)\n\n return -1 if ans==-float(\'inf\') else ans\n\n \n```
2
0
['Array', 'Hash Table', 'Python', 'Python3']
1
largest-positive-integer-that-exists-with-its-negative
🔥Beats 90% - No HashTable - O(1) Space | Clean Code | C++ |
beats-90-no-hashtable-o1-space-clean-cod-e98t
Code\n\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n \n int left = 0, right = nums.
Antim_Sankalp
NORMAL
2024-05-02T03:42:26.808464+00:00
2024-05-02T03:42:26.808483+00:00
2
false
# Code\n```\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n \n int left = 0, right = nums.size() - 1;\n while (left < right)\n {\n if (nums[left] == -nums[right])\n {\n return abs(nums[left]);\n }\n else if (abs(nums[left]) < abs(nums[right]))\n {\n right--;\n }\n else\n {\n left++;\n }\n }\n\n return -1;\n }\n};\n```
2
0
['C++']
0
largest-positive-integer-that-exists-with-its-negative
Simple java one pass HashSet solution
simple-java-one-pass-hashset-solution-by-amyq
\n# Approach\n# Explanation of findMaxK Method\nThis method aims to find the maximum value k such that both k and -k exist in the given array nums. It returns k
rohitmalekar2117
NORMAL
2024-05-02T03:41:45.120246+00:00
2024-05-02T03:41:45.120276+00:00
210
false
\n# Approach\n# Explanation of findMaxK Method\nThis method aims to find the maximum value k such that both k and -k exist in the given array nums. It returns k, or -1 if no such k exists.\n\n# Algorithm Overview\n1. Initialize a HashSet set to store encountered numbers and a variable maxNum to track the maximum value of k.\n2. Iterate through each element num in the array nums.\n3. Check if the negation of num exists in the set. If it does, update maxNum to the maximum of its current value and the absolute value of num.\n4. Add num to the set.\n5. After iterating through all elements, return maxNum.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\n public int findMaxK(int[] nums) {\n Set<Integer> set = new HashSet<>();\n int maxNum = -1;\n\n for(int num : nums){\n if(set.contains(-num))\n maxNum = Math.max(maxNum, Math.abs(num));\n \n set.add(num);\n }\n\n return maxNum;\n }\n}\n```
2
0
['Java']
2
largest-positive-integer-that-exists-with-its-negative
✅Beats 96% |🔥O(n) time and space complexity 🔥|🔥 Easy, Fast and Efficient using HashSet🔥🔥1 pass
beats-96-on-time-and-space-complexity-ea-4lmw
Intuition\nTo find the largest positive integer k such that -k also exists in the array, we can make array into hashset and iterate through the hashset and chec
darshan_anghan
NORMAL
2024-05-02T03:14:25.697646+00:00
2024-05-02T03:22:56.246100+00:00
12
false
# Intuition\nTo find the largest positive integer k such that -k also exists in the array, we can make array into hashset and iterate through the hashset and check if the negative of each number exists in the hashset.\n\n# Approach\nUse HashMap \n\n# Complexity\n- Time complexity:\nO(n) time complexity and only one for loop\n\n- Space complexity:\nO(n) Space complexity for store array into Hash-Table\n\n# Code\n```\nclass Solution {\n public int findMaxK(int[] nums) {\n int[] arr = new int[1001];\n int ind;\n int max= -1;\n\n for(int i=0; i<nums.length;i++){\n ind = Math.abs(nums[i]);\n if(arr[ind]!=0 && (arr[ind]+nums[i])==0 && Math.abs(nums[i])>max){ \n max=Math.abs(nums[i]); \n } \n else if(arr[ind]!=nums[i]){\n arr[ind] = nums[i]; \n }\n }\n return max;\n }\n}\n```
2
0
['Java']
1
largest-positive-integer-that-exists-with-its-negative
Java - using hashset
java-using-hashset-by-abhishekbalawan-fmjt
Store all the values in hashset.\n2. Iterate over all the numbers. For positive numbers, check if i\'ts negative counterpart exists. If so, check if it is large
abhishekbalawan
NORMAL
2024-05-02T03:13:38.960880+00:00
2024-05-02T03:13:38.960911+00:00
22
false
1. Store all the values in hashset.\n2. Iterate over all the numbers. For positive numbers, check if i\'ts negative counterpart exists. If so, check if it is largest value encoutered so far and update the answer accordingly.\n# class Solution {\n public int findMaxK(int[] nums) {\n HashSet<Integer> set = new HashSet();\n \n for(int num : nums){\n set.add(num);\n }\n \n int ans = -1;\n for(int num : nums){\n if(num>0 && set.contains(-1*num)){\n ans = Math.max(num, ans);\n }\n }\n \n return ans;\n }\n}
2
0
[]
0
largest-positive-integer-that-exists-with-its-negative
TWO POINTERS + SORT || Solution of largest positive integer that exists with its negative problem
two-pointers-sort-solution-of-largest-po-39ev
This was a daily challenge for May 2th 2024.\n\n# Approach\n- Given an integer array nums that does not contain any zeros, find the largest positive integer k s
tiwafuj
NORMAL
2024-05-02T01:45:02.924181+00:00
2024-05-02T01:45:02.924232+00:00
31
false
# This was a daily challenge for May 2th 2024.\n\n# Approach\n- Given an integer array nums that does not contain any zeros, find the largest positive integer `k` such that `-k` also exists in the array. Return the positive integer `k`. If there is no such integer, return `-1`.\n- We use two pointer technique for this problem. Two pointers is really an easy and effective technique that is typically used for searching pairs in a sorted array. The algorithm basically uses the fact that the input arrays are sorted.\n- We start from the zero and last index of the array and conditionally move both pointers. We move the right pointer when the value of the left pointer is less than the value of the right one in absolute value. The same logic applies to the left pointer. If both values \u200B\u200Bare equal to each other in absolute value, we return the answer. Otherwise we return -1\n\n# Complexity\n- Time complexity: $$O(nlogn)$$ - as we use `sort()` function\n- Space complexity: $$O(1)$$ - as no extra space is required\n\n# Code\n```\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n left, right = 0, len(nums) - 1\n nums.sort()\n while left < right and nums[left] < 0:\n if abs(nums[left]) == nums[right]:\n return nums[right]\n else:\n if abs(nums[left]) > nums[right]:\n left += 1\n else:\n right -= 1\n return -1\n```
2
0
['Array', 'Hash Table', 'Two Pointers', 'Sorting', 'Python3']
0
largest-positive-integer-that-exists-with-its-negative
Easy Solution|| Two Pointer approach
easy-solution-two-pointer-approach-by-sr-d8m1
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
sraj94956
NORMAL
2024-05-02T01:24:47.930601+00:00
2024-05-02T01:24:47.930638+00:00
225
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n sort(nums.begin(),nums.end(),greater<int>());\n for(int i=0;i<nums.size();i++){\n for(int j=i+1;j<nums.size();j++){\n if(nums[i]+nums[j]==0){\n return nums[i];\n }\n }\n }\n return -1;\n }\n};\n```
2
0
['C++']
0
largest-positive-integer-that-exists-with-its-negative
🔥 🔥 🔥 Simple solution in Python 🔥 🔥 🔥
simple-solution-in-python-by-bhanu_bhakt-thye
Intuition\n- Add all the existing nums in the set and search for the maxK which has -k and k.\n\n# Approach\n1. Add all the nums in the set.\n2. Assign maxNum a
bhanu_bhakta
NORMAL
2024-05-02T00:57:28.716390+00:00
2024-05-02T00:57:28.716407+00:00
3
false
# Intuition\n- Add all the existing nums in the set and search for the maxK which has -k and k.\n\n# Approach\n1. Add all the nums in the set.\n2. Assign maxNum as -1\n2. Iterate over the nums array and check if `-num` exists in the set, if so update the `maxNum` to: maxNum = max(maxNum, abs(num))\n3. Return the `maxNum`\n\n# Complexity\n- Time complexity:\nO(N)\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n # nums = [-1, 2, -3, 3]\n mySet = set(nums)\n maxNum = -1\n\n for num in nums:\n if -num in mySet:\n maxNum = max(maxNum, abs(num))\n \n return maxNum\n```
2
0
['Python3']
0
largest-positive-integer-that-exists-with-its-negative
💯✅Runtime 5 ms Beats 84.11% of users with Java||💯✅Memory 44.88 MB Beats 43.00% of users with Java
runtime-5-ms-beats-8411-of-users-with-ja-jmgp
Intuition\n Describe your first thoughts on how to solve this problem. \n- The given code aims to find the maximum value of k in an array of integers such that
suyalneeraj09
NORMAL
2024-05-02T00:56:42.696708+00:00
2024-05-08T00:25:01.373238+00:00
255
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- The given code aims to find the maximum value of k in an array of integers such that both k and -k exist in the array.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- The findMaxK method first checks for edge cases where the input array is null or empty, returning -1 in such cases.\n- It then sorts the input array in ascending order.\n\n- It iterates through the array, looking for negative values. For each negative value, it calculates its positive counterpart and searches for it in the array using the search method.\n- \n- The search method performs a binary search to find the index of the positive counterpart in the sorted array.\n- \n- If a positive counterpart is found, it returns the actual value of k; otherwise, it returns -1.\n# Complexity\n- Time complexity:O(n log n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nimport java.util.Arrays;\n\nclass Solution {\n public int findMaxK(int[] nums) {\n if (nums == null || nums.length == 0) {\n return -1; // Handle edge case of null or empty array\n }\n\n Arrays.sort(nums);\n\n for (int i = 0; i < nums.length && nums[i] < 0; i++) {\n int val = -nums[i];\n int index = search(nums, val);\n if (index >= 0) {\n return val; // Return the actual value of k\n }\n }\n\n return -1; // Return -1 if no matching positive value is found\n }\n\n private static int search(int[] arr, int t) {\n int s = 0;\n int e = arr.length - 1;\n\n while (s <= e) {\n int m = s + (e - s) / 2;\n if (arr[m] == t) {\n return m; // Return the index of the found element\n } else if (arr[m] < t) {\n s = m + 1;\n } else {\n e = m - 1;\n }\n }\n return -1; // Return -1 if the element is not found\n }\n}\n```\n![upvote.png](https://assets.leetcode.com/users/images/531e2611-2d66-4d79-b1a2-2834bdc0419a_1715127895.4791088.png)\n
2
0
['Array', 'Java']
3
largest-positive-integer-that-exists-with-its-negative
✅beats👊99% 💯Faster✅ Detailed Explanation
beats99-faster-detailed-explanation-by-d-rtzr
Intuition:\n# Given an array of integers, we need to find the maximum positive integer num such that its negation -num also exists in the array.\n# Approach:\n1
Dhruv__parmar
NORMAL
2024-05-02T00:24:20.935222+00:00
2024-05-02T00:24:20.935245+00:00
919
false
# Intuition:\n# **Given an array of integers, we need to find the maximum positive integer num such that its negation -num also exists in the array.**\n# Approach:\n1. **Create a set s containing all elements of the input array nums.**\n2. **Initialize a variable pair to -1, which will store the maximum positive integer that has a negation in the set.**\n3. **Iterate through each element num in the array nums.**\n4. **Check if num is positive and its negation -num exists in the set s.**\n5. **If both conditions are true, update pair to the maximum of its current value and num.**\n6. **Return the value of pair, which represents the maximum positive integer having its negation in the array.**\n# Complexity:\n- **Time complexity**:\nO(n)\n- **Space complexity**:\nO(n)\n# Code\n```Python []\nclass Solution:\n def findMaxK(self, nums: List[int]) -> int:\n s = set(nums)\n\n pair = -1\n for num in nums:\n if num > 0 and -num in s:\n pair = max(pair, num)\n return pair\n```\n```C++ []\nint findMaxK(vector<int>& nums) {\n unordered_set<int> s(nums.begin(), nums.end());\n int pair = -1;\n for (int num : nums) {\n if (num > 0 && s.count(-num)) {\n pair = max(pair, num);\n }\n }\n return pair;\n```\n```Java []\nclass Solution {\n public int findMaxK(int[] nums) {\n HashSet<Integer> set = new HashSet<>();\n for (int num : nums) {\n set.add(num);\n }\n int pair = -1;\n for (int num : nums) {\n if (num > 0 && set.contains(-num)) {\n pair = Math.max(pair, num);\n }\n }\n return pair;\n }\n}\n```\n
2
0
['Array', 'Hash Table', 'Two Pointers', 'Sorting', 'C++', 'Java', 'Python3']
2
largest-positive-integer-that-exists-with-its-negative
O(n) Time, O(1) Space Solution
on-time-o1-space-solution-by-django42-2nsi
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Django42
NORMAL
2024-04-23T11:33:50.679246+00:00
2024-04-23T11:33:50.679282+00:00
19
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\npublic class Solution {\n public int FindMaxK(int[] nums) {\n int[] pair = new int[1001];\n int max = -1;\n for (int i = 0; i < nums.Length; i++)\n {\n if (Math.Sign(nums[i]) == -1)\n {\n if (pair[nums[i] * -1] == nums[i] * -1)\n {\n max = Math.Max(max, nums[i] * -1);\n }\n else\n {\n pair[nums[i] * -1] = nums[i];\n }\n }\n else\n {\n if (pair[nums[i]] == nums[i] * -1)\n {\n max = Math.Max(max, nums[i]);\n }\n else\n {\n pair[nums[i]] = nums[i];\n }\n }\n }\n return max;\n }\n}\n```
2
0
['C#']
0
largest-positive-integer-that-exists-with-its-negative
Two Pointer || Sorting || 93% T.C || 66% S.C || CPP
two-pointer-sorting-93-tc-66-sc-cpp-by-g-2wom
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Ganesh_ag10
NORMAL
2024-04-20T02:04:02.178113+00:00
2024-04-20T02:04:02.178149+00:00
168
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n int i=0,j=nums.size()-1;\n sort(nums.begin(),nums.end()); \n while(i<j){\n int diff=nums[i]+nums[j];\n if(diff>0) j--;\n else if(diff<0) i++;\n else return nums[j];\n }\n return -1;\n }\n}; \n```
2
0
['C++']
1
largest-positive-integer-that-exists-with-its-negative
Beginner friendly , 2 pointers , Sorting Approach
beginner-friendly-2-pointers-sorting-app-w3cg
Intuition\nMax value required , hence first sorted and for searching 2 pointers\n\n# Approach\nHere , it is required that if in case we have more than 1 number
salNegi404
NORMAL
2024-03-10T09:09:39.472171+00:00
2024-03-10T09:09:39.472203+00:00
99
false
# Intuition\nMax value required , hence first sorted and for searching 2 pointers\n\n# Approach\nHere , it is required that if in case we have more than 1 number with +ve and -ve value we need to provide larger number.\n\nHence we first sorted the numbers. Then moving from end p2 (i.e larger value) we take its negative for comparission , if this negative value is lesser than the first value in sorted array(i.e 1st -ve val) example -10 < -7 , then it implies we have a +ve value for which we don\'t have a negative value in array it does not exist . Hence we move our p2 pointer to lesser index.\n\nAnd vice versa.\n\n# Complexity\n- Time complexity:\nO(n log n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n //[-7,-1,1,6,7,10] \n //This is how our sorted array look like \n sort(nums.begin(),nums.end());\n int p2=nums.size()-1;\n int p1=0;\n while(p1<p2){\n int neg = ~nums[p2]+1;\n if(nums[p1] == neg){\n return (nums[p2]);\n }\n else if(nums[p1]>neg){\n p2--;\n }\n else{\n p1++;\n }\n }\n return (-1);\n }\n};\n```
2
0
['C++']
0
largest-positive-integer-that-exists-with-its-negative
Simple easy cpp solution ✅✅
simple-easy-cpp-solution-by-vaibhav2112-eh5p
\n\n# Complexity \n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n)\n Add your space complexity here, e.g. O(n) \
vaibhav2112
NORMAL
2023-08-30T09:18:06.898192+00:00
2023-08-30T09:18:06.898212+00:00
110
false
\n\n# Complexity \n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n unordered_map<int,int> m;\n for(auto x: nums){\n m[x]++;\n }\n\n int ans = -1;\n\n for(auto x : m){\n int ele = -x.first;\n if(m.find(ele) != m.end() ){\n ans = max(ans,x.first);\n }\n }\n\n return ans;\n }\n};\n```
2
0
['C++']
0
largest-positive-integer-that-exists-with-its-negative
Easiest C++ Map Code
easiest-c-map-code-by-baibhavsingh07-516w
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
baibhavsingh07
NORMAL
2023-05-17T04:40:09.255213+00:00
2023-05-17T04:40:09.255246+00:00
171
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int findMaxK(vector<int>& a) {\n int i,j,k,ans=INT_MIN;\n unordered_map<int,int>m;\n for(auto x : a){\n if(m.find(-x)!=m.end())\n ans=max(abs(x),ans);\n\n m[x]++;\n }\n if(ans==INT_MIN)\n return -1;\n return ans;\n \n }\n};\n```
2
0
['Array', 'Hash Table', 'C++']
1
largest-positive-integer-that-exists-with-its-negative
C++ Easy Solution | | 4 Line Solution
c-easy-solution-4-line-solution-by-rhyth-dk4i
\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n int ans=-1;\n for(int it : nums)\n {\n if(it>0 && count(num
rhythm_jain_
NORMAL
2023-04-10T19:55:38.519050+00:00
2023-04-10T19:55:38.519096+00:00
436
false
```\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n int ans=-1;\n for(int it : nums)\n {\n if(it>0 && count(nums.begin(),nums.end(),-it)) ans=max(ans,it);\n }\n return ans;\n }\n};\n```
2
0
['C', 'C++']
1
largest-positive-integer-that-exists-with-its-negative
Easiest 5 liner approach(please upvote if you like the solution)
easiest-5-liner-approachplease-upvote-if-0mbn
Code\n\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n int l=0, h=nums.size()-1;\n whi
Tushar_Seth
NORMAL
2023-01-15T12:58:15.880787+00:00
2023-01-15T12:58:15.880839+00:00
30
false
# Code\n```\nclass Solution {\npublic:\n int findMaxK(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n int l=0, h=nums.size()-1;\n while(l < h)\n {\n if((nums[l] + nums[h]) == 0) return nums[h];\n else if((nums[l] + nums[h]) < 0) l++;\n else h--;\n }\n return -1;\n }\n};\n```
2
0
['C++']
0
find-nearest-point-that-has-the-same-x-or-y-coordinate
[Java/Python 3] Straight forward codes.
javapython-3-straight-forward-codes-by-r-leu3
Q & A\nQ1: Why have you initialized index with -1 and not 0?\n\nA1: Make the code more general. e.g., If no point has the same x or y coordinate, then we can st
rock
NORMAL
2021-03-06T16:11:49.455991+00:00
2021-04-29T15:42:08.035106+00:00
13,274
false
**Q & A**\nQ1: Why have you initialized index with `-1` and not `0`?\n\nA1: Make the code more general. e.g., If no point has the same `x` or `y` coordinate, then we can still detect it by the return value. Otherwise, if the return value is `0`, we would NOT know whether the point at index `0` is the solution or not.\n\n**End of Q & A**\n\n----\n\nExplanation by **@lionkingeatapple**\n\nBecause we want A point that shares the same `x`-coordinate or the same `y`-coordinate as your location, `dx * dy == 0` indicate either `dx` equals zero or `dy` equals zero, so we can make the product of `dx` and `dy` to be zero. `dx` and `dy` means the difference of `x`-coordinate and `y`-coordinate respectively. If the difference is zero, then they must be equal or shares the same `x/y`-coordinate.\n\nAlso, credit to **@KellyBundy** for improvement.\n\n```java\n public int nearestValidPoint(int x, int y, int[][] points) {\n int index = -1; \n for (int i = 0, smallest = Integer.MAX_VALUE; i < points.length; ++i) {\n int dx = x - points[i][0], dy = y - points[i][1];\n if (dx * dy == 0 && Math.abs(dy + dx) < smallest) {\n smallest = Math.abs(dx + dy);\n index = i;\n }\n }\n return index;\n }\n```\n\n```python\n def nearestValidPoint(self, x: int, y: int, points: List[List[int]]) -> int:\n index, smallest = -1, math.inf\n for i, (r, c) in enumerate(points):\n dx, dy = x - r, y - c\n if dx * dy == 0 and abs(dx + dy) < smallest:\n smallest = abs(dx + dy)\n index = i\n return index\n```
98
3
[]
9