 Open in App
Not now

# Longest subsequence from an array of pairs having first element increasing and second element decreasing.

• Last Updated : 09 Dec, 2022

Given an array of pairs A[][] of size N, the task is to find the longest subsequences where the first element is increasing and the second element is decreasing.

Examples:

Input: A[]={{1, 2}, {2, 2}, {3, 1}}, N = 3
Output: 2
Explanation: The longest subsequence satisfying the conditions is of length 2 and consists of {1, 2} and {3, 1};

Input: A[] = {{1, 3}, {2, 5}, {3, 2}, {5, 2}, {4, 1}}, N = 5
Output: 3

Naive Approach: The simplest approach is to use Recursion. For every pair in the array, there are two possible choices, i.e. either to include the current pair in the subsequence or not. Therefore, iterate over the array recursively and find the required longest subsequence.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach` `#include ` `using` `namespace` `std;`   `// Recursive function to find the length of` `// the longest subsequence of pairs whose first` `// element is increasing and second is decreasing` `int` `longestSubSequence(pair<``int``, ``int``> A[], ``int` `N,` `                       ``int` `ind = 0,` `                       ``int` `lastf = INT_MIN,` `                       ``int` `lasts = INT_MAX)` `{`   `    ``// Base case` `    ``if` `(ind == N)` `        ``return` `0;`   `    ``// Not include the current pair` `    ``// in the longest subsequence` `    ``int` `ans = longestSubSequence(A, N, ind + 1,` `                                 ``lastf, lasts);`   `    ``// Including the current pair` `    ``// in the longest subsequence` `    ``if` `(A[ind].first > lastf` `        ``&& A[ind].second < lasts)`   `        ``ans = max(ans, longestSubSequence(A, N, ind + 1,` `                                          ``A[ind].first,` `                                          ``A[ind].second)` `                           ``+ 1);`   `    ``return` `ans;` `}`   `// Driver Code` `int` `main()` `{` `    ``// Given Input` `    ``pair<``int``, ``int``> A[] = { { 1, 2 },` `                           ``{ 2, 2 },` `                           ``{ 3, 1 } };`   `    ``int` `N = ``sizeof``(A) / ``sizeof``(A);`   `    ``// Function Call` `    ``cout << longestSubSequence(A, N) << ``"\n"``;`   `    ``return` `0;` `}`

## Java

 `// Java program for the above approach` `import` `java.io.*;`   `class` `GFG{` `    `  `// Recursive function to find the length of` `// the longest subsequence of pairs whose first` `// element is increasing and second is decreasing` `public` `static` `Integer longestSubSequence(``int``[][] A, ``int` `N, ``int` `ind, ` `                                         ``int` `lastf, ``int` `lasts)` `{` `    ``ind = (ind > ``0` `? ind : ``0``);` `    ``lastf = (lastf > ``0` `? lastf: Integer.MIN_VALUE);` `    ``lasts = (lasts > ``0` `? lasts: Integer.MAX_VALUE);` `    `  `    ``// Base case` `    ``if` `(ind == N)` `        ``return` `0``;`   `    ``// Not include the current pair` `    ``// in the longest subsequence` `    ``int` `ans = longestSubSequence(A, N, ind + ``1``, ` `                                 ``lastf, lasts);`   `    ``// Including the current pair` `    ``// in the longest subsequence` `    ``if` `(A[ind][``0``] > lastf && A[ind][``1``] < lasts)`   `        ``ans = Math.max(ans, longestSubSequence(A, N, ind + ``1``, ` `                                   ``A[ind][``0``], A[ind][``1``]) + ``1``);`   `    ``return` `ans;` `}`   `public` `static` `int` `longestSubSequence(``int``[][] A, ``int` `N)` `{` `    ``return` `longestSubSequence(A, N, ``0``, ``0``, ``0``);` `}`   `// Driver Code` `public` `static` `void` `main(String args[]) ` `{` `    `  `    ``// Given Input` `    ``int``[][] A = { { ``1``, ``2` `}, { ``2``, ``2` `}, { ``3``, ``1` `} };` `    ``int` `N = A.length;`   `    ``// Function Call` `    ``System.out.println(longestSubSequence(A, N));` `}` `}`   `// This code is contributed by _saurabh_jaiswal`

## Python3

 `# Python 3 program for the above approach` `import` `sys`   `# Recursive function to find the length of` `# the longest subsequence of pairs whose first` `# element is increasing and second is decreasing` `def` `longestSubSequence(A,  N,` `                       ``ind``=``0``,` `                       ``lastf``=``-``sys.maxsize``-``1``,` `                       ``lasts``=``sys.maxsize):`   `    ``# Base case` `    ``if` `(ind ``=``=` `N):` `        ``return` `0`   `    ``# Not include the current pair` `    ``# in the longest subsequence` `    ``ans ``=` `longestSubSequence(A, N, ind ``+` `1``,` `                             ``lastf, lasts)`   `    ``# Including the current pair` `    ``# in the longest subsequence` `    ``if` `(A[ind][``0``] > lastf` `            ``and` `A[ind][``1``] < lasts):`   `        ``ans ``=` `max``(ans, longestSubSequence(A, N, ind ``+` `1``,` `                                          ``A[ind][``0``],` `                                          ``A[ind][``1``])` `                  ``+` `1``)`   `    ``return` `ans`     `# Driver Code` `if` `__name__ ``=``=` `"__main__"``:`   `    ``# Given Input` `    ``A ``=` `[[``1``, ``2``],` `         ``[``2``, ``2``],` `         ``[``3``, ``1``]]`   `    ``N ``=` `len``(A)` `    `  `    ``# Function Call` `    ``print``(longestSubSequence(A, N))`   `    ``# This code is contributed by ukasp.`

## C#

 `// C# program for the above approach` `using` `System;`   `class` `GFG{`   `// Recursive function to find the length of` `// the longest subsequence of pairs whose first` `// element is increasing and second is decreasing` `public` `static` `int` `longestSubSequence(``int``[,] A, ``int` `N, ``int` `ind, ` `                                         ``int` `lastf, ``int` `lasts)` `{` `    ``ind = (ind > 0 ? ind : 0);` `    ``lastf = (lastf > 0 ? lastf: Int32.MinValue);` `    ``lasts = (lasts > 0 ? lasts: Int32.MaxValue);` `    `  `    ``// Base case` `    ``if` `(ind == N)` `        ``return` `0;`   `    ``// Not include the current pair` `    ``// in the longest subsequence` `    ``int` `ans = longestSubSequence(A, N, ind + 1, ` `                                 ``lastf, lasts);`   `    ``// Including the current pair` `    ``// in the longest subsequence` `    ``if` `(A[ind, 0] > lastf && A[ind, 1] < lasts)`   `        ``ans = Math.Max(ans, longestSubSequence(A, N, ind + 1, ` `                                   ``A[ind, 0], A[ind, 1]) + 1);`   `    ``return` `ans;` `}`   `public` `static` `int` `longestSubSequence(``int``[,] A, ``int` `N)` `{` `    ``return` `longestSubSequence(A, N, 0, 0, 0);` `}`   `// Driver Code` `public` `static` `void` `Main()` `{` `    ``// Given Input` `    ``int``[,] A = { { 1, 2 }, { 2, 2 }, { 3, 1 } };` `    ``int` `N = A.GetLength(0);`   `    ``// Function Call` `    ``Console.Write(longestSubSequence(A, N));` `}` `}`   `// This code is contributed by target_2.`

## Javascript

 ``

Output

```2
```

Time Complexity: O(2N)
Auxiliary Space: O(1)

Efficient Approach: This problem has Overlapping Subproblems property and Optimal Substructure property. Therefore, this problem can be solved using Dynamic Programming. Like other typical Dynamic Programming (DP) problems, recomputation of same subproblems can be avoided by constructing a temporary array that stores the results of the subproblems.

Follow the steps below to solve this problem:

• Initialize a dp[] array, where dp[i] stores the length of the longest subsequence that can be formed using elements up to index i.
• Iterate over the range [0, N-1] using variable i:
• Base case: Update dp[i] as 1.
• Iterate over the range [0, i – 1] using a variable j:
•  If A[j].first is less than A[i].first and A[j].second is greater than A[i].second, then update dp[i] as maximum of dp[i] and dp[j] + 1.
• Finally, print dp[N-1].

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach`   `#include ` `using` `namespace` `std;`   `// Function to find the length of the` `// longest subsequence of pairs whose first` `// element is increasing and second is decreasing` `void` `longestSubSequence(pair<``int``, ``int``> A[], ``int` `N)` `{` `    ``// dp[i]: Stores the longest` `    ``// subsequence upto i` `    ``int` `dp[N];` `    ``for` `(``int` `i = 0; i < N; i++) {`   `        ``// Base case` `        ``dp[i] = 1;`   `        ``for` `(``int` `j = 0; j < i; j++) {`   `            ``// When the conditions hold` `            ``if` `(A[j].first < A[i].first` `                ``&& A[j].second > A[i].second) {`   `                ``dp[i] = max(dp[i], dp[j] + 1);` `            ``}` `        ``}` `    ``}`   `    ``// Finally, print the required answer` `    ``cout << dp[N - 1] << endl;` `}`   `// Driver Code` `int` `main()` `{` `    ``// Given Input` `    ``pair<``int``, ``int``> A[] = { { 1, 2 },` `                           ``{ 2, 2 },` `                           ``{ 3, 1 } };`   `    ``int` `N = ``sizeof``(A) / ``sizeof``(A);`   `    ``// Function Call` `    ``longestSubSequence(A, N);`   `    ``return` `0;` `}`

## Java

 `// Java program for the above approach` `import` `java.io.*;`   `class` `GFG{` `    `  `// Function to find the length of the` `// longest subsequence of pairs whose first` `// element is increasing and second is decreasing` `public` `static` `void` `longestSubSequence(``int``[][] A, ``int` `N)` `{` `    `  `    ``// dp[i]: Stores the longest` `    ``// subsequence upto i` `    ``int``[] dp = ``new` `int``[N];` `    `  `    ``for``(``int` `i = ``0``; i < N; i++)` `    ``{` `        `  `        ``// Base case` `        ``dp[i] = ``1``;`   `        ``for``(``int` `j = ``0``; j < i; j++)` `        ``{` `            `  `            ``// When the conditions hold` `            ``if` `(A[j][``0``] < A[i][``0``] && A[j][``1``] > A[i][``1``])` `            ``{` `                ``dp[i] = Math.max(dp[i], dp[j] + ``1``);` `            ``}` `        ``}` `    ``}`   `    ``// Finally, print the required answer` `    ``System.out.println(dp[N - ``1``]);` `}`   `// Driver Code` `public` `static` `void` `main(String args[])` `{` `    `  `    ``// Given Input` `    ``int``[][] A = { { ``1``, ``2` `},` `                  ``{ ``2``, ``2` `},` `                  ``{ ``3``, ``1` `} };`   `    ``int` `N = A.length;`   `    ``// Function Call` `    ``longestSubSequence(A, N);` `}` `}`   `// This code is contributed by gfgking`

## Python3

 `# Python3 program for the above approach`   `# Function to find the length of the` `# longest subsequence of pairs whose first` `# element is increasing and second is decreasing` `def` `longestSubSequence(A, N):` `  `  `    ``# dp[i]: Stores the longest` `    ``# subsequence upto i` `    ``dp ``=` `[``0``]``*``N` `    ``for` `i ``in` `range``(N):` `      `  `        ``# Base case` `        ``dp[i] ``=` `1`   `        ``for` `j ``in` `range``(i):` `          `  `            ``# When the conditions hold` `            ``if` `(A[j][``0``] < A[i][``0``] ``and` `A[j][``1``] > A[i][``1``]):` `                ``dp[i] ``=` `max``(dp[i], dp[j] ``+` `1``)`     `    ``# Finally, print the required answer` `    ``print` `(dp[N ``-` `1``])`   `# Driver Code` `if` `__name__ ``=``=` `'__main__'``:` `  `  `    ``#Given Input` `    ``A ``=` `[ [ ``1``, ``2` `],` `           ``[ ``2``, ``2` `],` `           ``[ ``3``, ``1` `] ]`   `    ``N ``=` `len``(A)`   `    ``#Function Call` `    ``longestSubSequence(A, N)`   `# This code is contributed by mohit kumar 29.`

## C#

 `// C# program for the above approach` `using` `System;` `class` `GFG {` `    `  `    ``// Function to find the length of the` `    ``// longest subsequence of pairs whose first` `    ``// element is increasing and second is decreasing` `    ``static` `void` `longestSubSequence(``int``[,] A, ``int` `N)` `    ``{` `         `  `        ``// dp[i]: Stores the longest` `        ``// subsequence upto i` `        ``int``[] dp = ``new` `int``[N];` `         `  `        ``for``(``int` `i = 0; i < N; i++)` `        ``{` `             `  `            ``// Base case` `            ``dp[i] = 1;` `     `  `            ``for``(``int` `j = 0; j < i; j++)` `            ``{` `                 `  `                ``// When the conditions hold` `                ``if` `(A[j,0] < A[i,0] && A[j,1] > A[i,1])` `                ``{` `                    ``dp[i] = Math.Max(dp[i], dp[j] + 1);` `                ``}` `            ``}` `        ``}` `     `  `        ``// Finally, print the required answer` `        ``Console.Write(dp[N - 1]);` `    ``}`   `  ``static` `void` `Main() ` `  ``{` `    `  `    ``// Given Input` `    ``int``[,] A = { { 1, 2 },` `                  ``{ 2, 2 },` `                  ``{ 3, 1 } };` ` `  `    ``int` `N = A.GetLength(0);` ` `  `    ``// Function Call` `    ``longestSubSequence(A, N);` `  ``}` `}`   `// This code is contributed by decode2207.`

## Javascript

 ``

Output

```2
```

Time Complexity: O(N2)
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up
Related Articles