
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Length of Longest Sign Alternating Subsequence in Python
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 −
Example
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
Advertisements