K and -K in Python

PythonServer Side ProgrammingProgramming

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 −

  • L1:= a list of 0 and positive elements in nums
  • L2:= a list of 0 and negative elements in nums
  • sort L1 in reverse order
  • sort the list L2
  • for each i in L1, do
    • for each j in L2, do
      • if i+j is same as 0, then
        • return i
      • otherwise when i+j > 0 , then
        • come out from the current loop
  • return -1

Let us see the following implementation to get better understanding −

Example

 Live Demo

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))

Input

[-5, 2, 9, -6, 5, -9]

Output

9
raja
Published on 23-Sep-2020 07:25:49
Advertisements