Leetcode 2441: Largest Positive Integer That Exists With Its Negative

grid47
grid47
Exploring patterns and algorithms
Mar 7, 2024 5 min read

You are given an integer array nums where each element is non-zero. Your task is to find the largest positive integer k such that its negative counterpart -k also exists in the array. Return the largest such k. If no such integer exists, return -1.
Problem
Approach
Steps
Complexity
Input: The input is a non-empty array `nums` of integers, where each integer is non-zero.
Example: nums = [4, -2, -4, 5, 1]
Constraints:
• 1 <= nums.length <= 1000
• -1000 <= nums[i] <= 1000
• nums[i] != 0
Output: Return the largest integer `k` such that `-k` exists in the array. If no such `k` exists, return -1.
Example: Output: 4
Constraints:
• The returned result must be an integer.
Goal: The goal is to find the largest integer `k` such that `-k` exists in the array.
Steps:
• 1. Iterate through the array and store the presence of each number in a hash map.
• 2. For each positive integer `k` in the array, check if its negative counterpart `-k` is also present.
• 3. Track the largest valid `k` found during the iteration and return it.
Goal: The solution should handle arrays of size up to 1000 and should be able to efficiently find the largest `k`.
Steps:
• Arrays will always contain non-zero integers.
Assumptions:
• The input array will always contain at least one element.
• There will be no zeroes in the input array.
Input: nums = [4, -2, -4, 5, 1]
Explanation: Here, the number `4` has its negative counterpart `-4` in the array. The number `2` has `-2`, but the largest such integer is `4`. Hence, the output is 4.

Input: nums = [-6, -3, 5, 2]
Explanation: There is no positive integer `k` such that `-k` is present in the array. Therefore, the output is -1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus