Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

2441. Largest Positive Integer That Exists With Its Negative

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.

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;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.