- 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
Program to find length of longest consecutive sublist with unique elements in Python
Suppose we have a list of numbers called nums, where all elements are unique. We have to find the length of the longest sublist that contains consecutive elements.
So, if the input is like nums = [3, 6, 7, 5, 4, 9], then the output will be 5, because the sublist is [3, 6, 7, 5, 4] this contains all consecutive elements from 3 to 7.
To solve this, we will follow these steps −
- ret := 0
- for i in range 0 to size of nums - 1, do
- lhs := nums[i]
- rhs := nums[i]
- for j in range i to size of nums - 1, do
- lhs := minimum of lhs and nums[j]
- rhs := maximum of rhs and nums[j]
- if (rhs - lhs) is same as (j - i), then
- ret := maximum of ret and (j - i + 1)
- return ret
Example
Let us see the following implementation to get better understanding −
def solve(nums): ret = 0 for i in range(len(nums)): lhs = nums[i] rhs = nums[i] for j in range(i, len(nums)): lhs = min(lhs, nums[j]) rhs = max(rhs, nums[j]) if rhs - lhs == j - i: ret = max(ret, j - i + 1) return ret nums = [3, 6, 7, 5, 4, 9] print(solve(nums))
Input
[3, 6, 7, 5, 4, 9]
Output
1
Advertisements
To Continue Learning Please Login
Login with Google