Suppose we have a list of numbers called nums, we have to find the largest number k where k and -k both exist in nums (they can be the same number). If there's no such element, return -1.
So, if the input is like [-5, 2, 9, -6, 5, -9], then the output will be 9.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
class Solution: def solve(self, nums): L1=[i for i in nums if i>=0] L2=[i for i in nums if i<=0] L1.sort(reverse=True) L2.sort() for i in L1: for j in L2: if i+j==0: return i elif i+j>0: break return -1 ob = Solution() nums = [-5, 2, 9, -6, 5, -9] print(ob.solve(nums))
[-5, 2, 9, -6, 5, -9]