- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- 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

Suppose we have a list of numbers called nums, we have to find the size of the longest subsequence where the difference between two consecutive numbers alternate between positive and negative. And the first difference may be either positive or negative.

So, if the input is like nums = [6, 10, 4, 2, 3, 9, 4, 7], then the output will be 6, as on possible required subsequence is [6, 10, 2, 9, 4, 7] and the differences are [4, -8, 7, -5, 3].

To solve this, we will follow these steps &minuS;

- n := size of nums
- dp := a list of size 2n and fill with 1
- ans := 0
- for i in range 0 to n, do
- for j in range 0 to i, do
- if nums[j] < nums[i], then
- dp[i, 0] = maximum of dp[i, 0] and (dp[j, 1] + 1)

- otherwise when nums[j] > nums[i], then
- dp[i, 1] = maximum of dp[i, 1] and (dp[j, 0] + 1)

- if nums[j] < nums[i], then
- ans = maximum of ans, dp[i, 0] and dp[i, 1])

- for j in range 0 to i, do
- return ans

Let us see the following implementation to get better understanding −

class Solution: def solve(self, nums): n = len(nums) dp = [[1] * 2 for _ in range(n)] ans = 0 for i in range(n): for j in range(i): if nums[j] < nums[i]: dp[i][0] = max(dp[i][0], dp[j][1] + 1) elif nums[j] > nums[i]: dp[i][1] = max(dp[i][1], dp[j][0] + 1) ans = max(ans, dp[i][0], dp[i][1]) return ans ob = Solution() nums = [6, 10, 4, 2, 3, 9, 4, 7] print(ob.solve(nums))

[6, 10, 4, 2, 3, 9, 4, 7]

6

- Related Questions & Answers
- Program to find length of longest sign alternating subsequence from a list of numbers 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 fibonacci subsequence in Python
- Program to find length of longest alternating inequality elements sublist in Python
- Program to find length of longest alternating path of a binary tree in python
- Program to find length of longest circular increasing subsequence 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 length of longest interval from a list of intervals in Python
- Program to find length of longest common subsequence of three strings in Python

Advertisements