diff --git a/2441.largest-positive-integer-that-exists-with-its-negative.js b/2441.largest-positive-integer-that-exists-with-its-negative.js new file mode 100644 index 00000000..543aa871 --- /dev/null +++ b/2441.largest-positive-integer-that-exists-with-its-negative.js @@ -0,0 +1,22 @@ +/* URL of this problem + * https://leetcode.com/problems/largest-positive-integer-that-exists-with-its-negative/description/ + * + * @param {number[]} nums + * @return {number} + */ + +var findMaxK = function(nums) { + // Sort the input nums in a descending order + const Sorted = [...nums].sort((a, b) => b - a); + + for (let i = 0; i < Sorted.length; i++) { + const Num = Sorted[i]; + + if (Sorted.includes(Num * -1)) { + return Num; + } + } + return -1; +}; + +module.exports = findMaxK; \ No newline at end of file diff --git a/findMaxK.test.js b/findMaxK.test.js new file mode 100644 index 00000000..4484b18c --- /dev/null +++ b/findMaxK.test.js @@ -0,0 +1,17 @@ +const findMaxK = require("./2441.largest-positive-integer-that-exists-with-its-negative"); + +test("Return the largest positive integer k such that -k also exists in the array", () => { + expect(findMaxK([-1,2,-3,3])).toBe(3); +}); + +test("Return -1 if there is no such a positive integer k that -k also exists in the array", () => { + expect(findMaxK([-10,8,6,7,-2,-3])).toBe(-1); +}); + +test("Return Infinity if the array contains Infinity and -Infinity", () => { + expect(findMaxK([Infinity, -Infinity])).toBe(Infinity); +}); + +test("Return 0 if the array contains only zeroes", () => { + expect(findMaxK([0,0])).toBe(0); +}); \ No newline at end of file