Quantcast
Channel: Coddicted
Viewing all articles
Browse latest Browse all 10

Solved! Leetcode 2441. Largest Positive Integer That Exists With Its Negative

$
0
0

Description: Largest Positive Integer That Exists With Its Negative

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.

Example 1

<strong>Input:</strong> nums = [-1,2,-3,3]
<strong>Output:</strong> 3
<strong>Explanation:</strong> 3 is the only valid k we can find in the array.

Example 2

<strong>Input:</strong> nums = [-1,10,6,7,-7,1]
<strong>Output:</strong> 7
<strong>Explanation:</strong> Both 1 and 7 have their corresponding negative values in the array. 7 has a larger value.

Example 3

<strong>Input:</strong> nums = [-10,8,6,7,-2,-3]
<strong>Output:</strong> -1
<strong>Explanation:</strong> There is no a single valid k, we return -1.

Constraints

  • 1 <= nums.length <= 1000
  • -1000 <= nums[i] <= 1000
  • nums[i] != 0

Solution

class Solution {
    //edge cases
    //&#91;-30, -30]
    //&#91;-30, 30, -30]
    //&#91;-1, 1, -1, -1, -1]
    public int findMaxK(int&#91;] nums) {
        int&#91;] pos = new int&#91;1001];
        int&#91;] neg = new int&#91;1001];
        for(int n: nums){
            if(n&lt;0)
                neg&#91;Math.abs(n)]++;
            else
                pos&#91;n]++;
        }

        for(int i=1000;i&gt;=1;i--){
            if(pos&#91;i]&gt;0 &amp;&amp; neg&#91;i]&gt;0){
                return i;
            }
        }

        return -1;
    }
}

Time Complexity

O(1), fixed length array

Space Complexity

O(1)

Rate this post


Viewing all articles
Browse latest Browse all 10

Trending Articles