Program to find length of longest consecutive sublist with unique elements in Python

PythonServer Side ProgrammingProgramming

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
raja
Updated on 19-Oct-2021 13:43:10

Advertisements