
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 Alternating Subsequence in Python
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
Example (Python)
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))
Input
[6, 10, 4, 2, 3, 9, 4, 7]
Output
6
Advertisements