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

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

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