DEV Community

Cover image for 2441. Largest Positive Integer That Exists With Its Negative
MD ARIFUL HAQUE
MD ARIFUL HAQUE

Posted on • Edited on

2441. Largest Positive Integer That Exists With Its Negative

2441. Largest Positive Integer That Exists With Its Negative

Easy

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:

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

Example 2:

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

Example 3:

  • Input: nums = [-10,8,6,7,-2,-3]
  • Output: -1
  • Explanation: 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 {

    /**
     * @param Integer[] $nums
     * @return Integer
     */
    function findMaxK($nums) {
        $ans = -1;
        $seen = [];

        foreach ($nums as $num) {
            if (in_array(-$num, $seen)) {
                $ans = max($ans, abs($num));
            } else {
                array_push($seen, $num);
            }
        }

        return $ans;
    }
}
Enter fullscreen mode Exit fullscreen mode

Contact Links

If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay