LeetCode 2441: Largest Positive Integer That Exists With Its Negative Solution

Master LeetCode problem 2441 (Largest Positive Integer That Exists With Its Negative), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2441. Largest Positive Integer That Exists With Its Negative

Problem Explanation

Explanation

To solve this problem, we can iterate through the given array and keep track of the positive integers we encounter. For each positive integer, we check if its negative counterpart exists in the array. If a negative counterpart exists, we update the largest positive integer found so far. Finally, we return the largest positive integer or -1 if no such integer exists.

  • Start with a variable maxPositive initialized to -1.
  • Iterate through the array:
    • If the current element is positive and its negative counterpart exists in the array:
      • Update maxPositive if the current element is greater than maxPositive.
  • Return maxPositive.

The time complexity of this solution is O(n) where n is the number of elements in the array, as we iterate through the array once. The space complexity is O(1) as we use only a constant amount of extra space.

Solution Code

class Solution {
    public int largestPositiveInteger(int[] nums) {
        int maxPositive = -1;
        
        for (int num : nums) {
            if (num > 0 && containsNegative(nums, -num)) {
                maxPositive = Math.max(maxPositive, num);
            }
        }
        
        return maxPositive;
    }
    
    private boolean containsNegative(int[] nums, int target) {
        for (int num : nums) {
            if (num == target) {
                return true;
            }
        }
        return false;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2441 (Largest Positive Integer That Exists With Its Negative)?

This page provides optimized solutions for LeetCode problem 2441 (Largest Positive Integer That Exists With Its Negative) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2441 (Largest Positive Integer That Exists With Its Negative)?

The time complexity for LeetCode 2441 (Largest Positive Integer That Exists With Its Negative) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2441 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2441 in Java, C++, or Python.

Back to LeetCode Solutions