Program to find length of longest sign alternating subsequence from a list of numbers in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of numbers called nums, we have to find the length of longest subsequence that flips sign on each consecutive number.

So, if the input is like nums = [1, 3, -6, 4, -3], then the output will be 4, as we can pick [1, -6, 4, -3].

To solve this, we will follow these steps −

  • pos := 0, neg := 0
  • for each n in nums, do
    • if n < 0, then
      • neg := pos + 1
    • otherwise,
      • pos := neg + 1
  • return maximum of pos and neg

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, nums):
      pos = neg = 0
      for n in nums:
         if n < 0:
            neg = pos + 1
         else:
            pos = neg + 1
      return max(pos, neg)
ob = Solution()
nums = [1, 3, -6, 4, -3]
print(ob.solve(nums))

Input

[1, 3, -6, 4, -3]

Output

4
raja
Published on 19-Nov-2020 11:47:35
Advertisements