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

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