![]() |
VOOZH | about |
Given an array arr[] of N integers and an integer D, the task is to find the length of the longest non-decreasing subsequence such that the difference between every adjacent element is less than D.
Examples:
Input: arr[] = {1, 3, 2, 4, 5}, D = 2
Output: 3
Explanation:
Consider the subsequence as {3, 4, 5}, which is of maximum length = 3 satisfying the given criteria.Input: arr[] = {1, 5, 3, 2, 7}, D = 2
Output: 2
Approach: The given problem is a variation of Longest Increasing Subsequence with criteria for the difference between adjacent array elements as less than D, this idea can be implemented using Dynamic Programming. Follow the steps below to solve the given problem:
Below is the implementation of the above approach:
3
Time Complexity: O(N2)
Auxiliary Space: O(N)