Program to find length of longest contiguously strictly increasing sublist after removal in Python


Suppose we have a list of numbers called nums, we have to find the maximum length of a contiguous strictly increasing sublist. We are allowed to remove at most single element from the list.

So, if the input is like nums = [35, 5, 6, 7, 8, 9, 12, 11, 26], then the output will be 7, because if we remove 12 from nums, the list will be [5, 6, 7, 8, 9, 11, 26], the length is 7, this is the longest, contiguous, strictly increasing sub-list.

To solve this, we will follow these steps −

  • if nums is empty, then
    • return 0
  • end := a list of size same as nums and fill with 1
  • start := a list of size same as nums and fill with 1
  • for i in range 1 to size of nums - 1, do
    • if nums[i] > nums[i - 1], then
      • end[i] := end[i - 1] + 1
  • for j in range size of nums - 2 to 0, decrease by 1, do
    • if nums[j + 1] > nums[j], then
      • start[j] := start[j + 1] + 1
  • res := maximum of the elements of end and element of start
  • for k in range 1 to size of nums - 2, do
    • if nums[k - 1] < nums[k + 1], then
      • res := maximum of res and (end[k - 1] + start[k + 1])
  • return res

Example

Let us see the following implementation to get better understanding −

def solve(nums):
   if not nums:
      return 0
   end = [1 for i in nums]
   start = [1 for i in nums]

   for i in range(1, len(nums)):
      if nums[i] > nums[i - 1]:
         end[i] = end[i - 1] + 1

   for j in range(len(nums) - 2, -1, -1):
      if nums[j + 1] > nums[j]:
         start[j] = start[j + 1] + 1

   res = max(max(end), max(start))

   for k in range(1, len(nums) - 1):
      if nums[k - 1] < nums[k + 1]:
         res = max(res, end[k - 1] + start[k + 1])

   return res

nums = [35, 5, 6, 7, 8, 9, 12, 11, 26]
print(solve(nums))

Input

[35, 5, 6, 7, 8, 9, 12, 11, 26]

Output

7

Updated on: 19-Oct-2021

374 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements