Leetcode 2441. Largest Positive Integer That Exists With Its Negative
Given an integer array nums that does not contain any zero, find the largest positive integer k such that -k is also in nums. If there is no such integer, return -1.
k for which both k and -k exist in the set.#include <vector>
#include <unordered_set>
#include <algorithm>
int findMaxK(std::vector<int>& nums) {
std::unordered_set<int> numSet;
int largestK = -1;
for (int num : nums) {
numSet.insert(num);
}
for (int num : nums) {
if (num > 0 && numSet.find(-num) != numSet.end()) {
largestK = std::max(largestK, num);
}
}
return largestK;
}
numSet) is used to store all elements from the array. This allows us to quickly check the presence of -k.k, check if -k exists in the set. Keep track of the maximum k found.n is the number of elements in the array.This approach ensures that we efficiently find the largest integer k such that both k and -k exist in the array.
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?