- Related Questions & Answers
- Program to find length of longest alternating subsequence from a given list in Python
- Program to find length of longest Fibonacci subsequence from a given list in Python
- Program to find length of longest arithmetic subsequence of a given list in Python
- Program to find length of longest balanced subsequence in Python
- Program to find length of longest anagram subsequence in Python
- Program to find length of longest increasing subsequence in Python
- Program to find length of longest palindromic subsequence in Python
- Program to find length of longest alternating path of a binary tree in python
- Program to find length of longest alternating inequality elements sublist in Python
- Program to find length of longest circular increasing subsequence in python
- Program to find length of longest interval from a list of intervals in Python
- Program to find length of longest common subsequence of three strings in Python
- Program to find length of longest common subsequence in C++
- Program to find length of longest bitonic subsequence in C++
- Program to find out the length of longest palindromic subsequence using Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

- if n < 0, then
- return maximum of pos and neg

Let us see the following implementation to get better understanding −

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))

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

4

Advertisements