- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
K and -K in Python
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
- if i+j is same as 0, then
- for each j in L2, do
- return -1
Let us see the following implementation to get better understanding −
Example
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
Advertisements