Program to find length of contiguous strictly increasing sublist in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of numbers called nums, we have to find the maximum length of a contiguous strictly increasing sublist when we can remove one or zero elements from the list.

So, if the input is like nums = [30, 11, 12, 13, 14, 15, 18, 17, 32], then the output will be 7, as when we remove 18 in the list we can get [11, 12, 13, 14, 15, 17, 32] which is the longest, contiguous, strictly increasing sublist, and its length is 7.

To solve this, we will follow these steps−

  • n := size of nums

  • pre := a list of size n and fill with 1s

  • for i in range 1 to n - 1, do

    • if nums[i] > nums[i - 1], then

      • pre[i] := pre[i - 1] + 1

  • suff := a list of size n and fill with 1s

  • for i in range n - 2 to -1, decrease by 1, do

    • if nums[i] < nums[i + 1], then

      • suff[i] := suff[i + 1] + 1

  • ans := maximum value of maximum of pre and maximum of suff

  • for i in range 1 to n - 1, do

    • if nums[i - 1] < nums[i + 1], then

      • ans := maximum of ans and (pre[i - 1] + suff[i + 1])

  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, nums):
      n = len(nums)
      pre = [1] * n
      for i in range(1, n - 1):
         if nums[i] > nums[i - 1]:
            pre[i] = pre[i - 1] + 1
      suff = [1] * n
      for i in range(n - 2, -1, -1):
         if nums[i] < nums[i + 1]:
            suff[i] = suff[i + 1] + 1
               ans = max(max(pre), max(suff))
               for i in range(1, n - 1):
                  if nums[i - 1] < nums[i + 1]:
                     ans = max(ans, pre[i - 1] + suff[i + 1])
               return ans
ob = Solution()
nums = [30, 11, 12, 13, 14, 15, 18, 17, 32]
print(ob.solve(nums))

Input

[30, 11, 12, 13, 14, 15, 18, 17, 32]

Output

7
raja
Published on 06-Oct-2020 10:05:39
Advertisements