Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions 2441.largest-positive-integer-that-exists-with-its-negative.js
Original file line number Diff line number Diff line change
@@ -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;
17 changes: 17 additions & 0 deletions findMaxK.test.js
Original file line number Diff line number Diff line change
@@ -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);
});