Warning: Undefined array key "amp-addthis" in /home/tgagmvup/onlinestudy.guru/wp-content/plugins/addthis/backend/AddThisSharingButtonsFeature.php on line 101
lang="en-US"> Largest Positive Integer 2441
Site icon onlinestudy.guru

2441. Largest Positive Integer That Exists With Its Negative

Largest Positive Integer

Largest Positive Integer

class Solution {
    public int findMaxK(int[] nums) {

        HashSet<Integer> numSet = new HashSet<>();
        int maxK = -1;

        // Adding all numbers to the set
        for (int num : nums) {
            numSet.add(num);
        }

        // Iterating through the array to find the largest positive integer k
        for (int num : nums) {
            if (numSet.contains(-num) && num > 0) {
                maxK = Math.max(maxK, num);
            }
        }

        // Returning the result
        return maxK;
    }
}

This Java code defines a method findMaxK within a class Solution. The purpose of this method is to find the largest positive integer k such that its negative counterpart -k exists in the given array nums.

Here’s a breakdown of how the code works:

  1. Initialization:
  1. Adding numbers to the set:
  1. Finding the largest positive integer k:
  1. Returning the result:

Overall, this method efficiently finds the largest positive integer k such that -k exists in the given array. If no such k is found, the method returns -1.

Exit mobile version