Leetcode 2441. Largest Positive Integer That Exists With Its Negative
You are 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.
Let’s implement this strategy in Java:
import java.util.HashSet;
public class Solution {
public int findMaxK(int[] nums) {
HashSet<Integer> set = new HashSet<>();
int maxK = -1;
// Add all elements to the set
for (int num : nums) {
set.add(num);
}
// Check for the largest positive number k such that -k exists
for (int num : nums) {
if (num > 0 && set.contains(-num)) {
maxK = Math.max(maxK, num);
}
}
return maxK;
}
// Example test for verification
public static void main(String[] args) {
Solution solution = new Solution();
int[] nums = {3, 2, -2, 5, -3};
System.out.println(solution.findMaxK(nums)); // Output should be 3
}
}
k
also takes O(n).Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?