2441. Largest Positive Integer That Exists With Its Negative

shashi
2 min readMay 2, 2024

--

Solved
Easy
Topics
Companies
Hint
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. the positive integer k. If there is no such integer, return -1.

Example 1:

Input: nums = [-1,2,-3,3]
Output: 3
Explanation: 3 is the only valid k we can find in the array.
Example 2:

Input: nums = [-1,10,6,7,-7,1]
Output: 7
Explanation: Both 1 and 7 have their corresponding negative values in the array. 7 has a larger value.
Example 3:

Input: nums = [-10,8,6,7,-2,-3]
Output: -1
Explanation: There is no a single valid k, we return -1.

Constraints:

1 <= nums.length <= 1000
-1000 <= nums[i] <= 1000
nums[i] != 0

class Solution {
public int findMaxK1(int[] nums) {
Arrays.sort(nums);
Set<Integer> hset=new HashSet<>();
for(int i: nums){
hset.add(i);
}

for(int i=nums.length-1; i>=0; i--) {
if(hset.contains(-1*nums[i])){
return nums[i];
}
}
return -1;
}

public int findMaxK(int[] nums) {
int max=Integer.MIN_VALUE;
Set<Integer> hset=new HashSet<>();
for(int i: nums){
if(hset.contains(-1*i)){
max=Math.max(max,Math.abs(i));
}
hset.add(i);
}
return max==Integer.MIN_VALUE? -1:max;
}
}

/**
2441. Largest Positive Integer That Exists With Its Negative
Solved
Easy
Topics
Companies
Hint
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.



Example 1:

Input: nums = [-1,2,-3,3]
Output: 3
Explanation: 3 is the only valid k we can find in the array.
Example 2:

Input: nums = [-1,10,6,7,-7,1]
Output: 7
Explanation: Both 1 and 7 have their corresponding negative values in the array. 7 has a larger value.
Example 3:

Input: nums = [-10,8,6,7,-2,-3]
Output: -1
Explanation: There is no a single valid k, we return -1.

Constraints:

1 <= nums.length <= 1000
-1000 <= nums[i] <= 1000
nums[i] != 0

*/

--

--

shashi
shashi

No responses yet