Microsoft Online Assessment (OA) - Largest K such that both K and -K exist in array

Given an array A of N integers, returns the largest integer K > 0 such that both values K and -K exist in array A. If there is no such integer, the function should return 0.

Example 1:

Input:[3, 2, -2, 5, -3]

Output: 3

Example 2:

Input:[1, 2, 3, -4]

Output: 0

Try it yourself

Implementation

1from typing import List
2
3def largest_k(nums: List[int]) -> int:
4    result = 0
5    for i in nums:
6        if i < 0 and -i in nums:
7            result = max(result, -i)
8    return result
9
10if __name__ == '__main__':
11    nums = [int(x) for x in input().split()]
12    res = largest_k(nums)
13    print(res)
14