Program to find length of longest alternating inequality elements sublist in Python


Suppose we have a list of mumbers called nums, and find the length of the longest sublist in nums such that the equality relation between every consecutive numbers changes alternatively between less-than and greater-than operation. The first two numbers' inequality may be either less-than or greater-than.

So, if the input is like nums = [1, 2, 6, 4, 5], then the output will be 4, as the longest inequality alternating sublist is [2, 6, 4, 5] as 2 < 6 > 4 < 5.

To solve this, we will follow these steps −

  • Define a function get_direction(). This will take a, b

    • return 0 if a is same as b otherwise -1 if a < b otherwise 1

  • if size of nums < 2, then

    • return size of nums

  • max_length := 1, cur_length := 1, last_direction := 0

  • for i in range 0 to size of nums - 1, do

    • direction := get_direction(nums[i], nums[i + 1])

    • if direction is same as 0, then

      • cur_length := 1

    • otherwise when direction is same as last_direction, then

      • cur_length := 2

    • otherwise,

      • cur_length := cur_length + 1

    • max_length := maximum of max_length and cur_length

    • last_direction := direction

  • return max_length

Let us see the following implementation to get better understanding−

Example

 Live Demo

class Solution:
   def solve(self, nums):
      if len(nums) < 2:
         return len(nums)
      def get_direction(a, b):
         return 0 if a == b else -1 if a < b else 1
      max_length = 1
      cur_length = 1
      last_direction = 0
      for i in range(len(nums) - 1):
         direction = get_direction(nums[i], nums[i + 1])
         if direction == 0:
            cur_length = 1
         elif direction == last_direction:
            cur_length = 2
         else:
            cur_length += 1
         max_length = max(max_length, cur_length)
         last_direction = direction
      return max_length
ob = Solution()
nums = [1, 2, 6, 4, 5]
print(ob.solve(nums))

Input

[1, 2, 6, 4, 5]

Output

4

Updated on: 10-Oct-2020

127 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements