📌  相关文章
📜  来自具有第一个元素增加和第二个元素减少的对数组的最长子序列。

📅  最后修改于: 2021-09-17 07:37:40             🧑  作者: Mango

给定大小为N 的A[][]对数组,任务是找到第一个元素增加而第二个元素减少的最长子序列。

例子:

朴素的方法:最简单的方法是使用递归。对于数组中的每一对,有两种可能的选择,即在子序列中包括或不包括当前对。因此,递归遍历数组并找到所需的最长子序列。

下面是上述方法的实现:

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 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 A[] = { { 1, 2 },
                           { 2, 2 },
                           { 3, 1 } };
 
    int N = sizeof(A) / sizeof(A[0]);
 
    // Function Call
    cout << longestSubSequence(A, N) << "\n";
 
    return 0;
}


Java
// Java program for the above approach
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


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 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 A[] = { { 1, 2 },
                           { 2, 2 },
                           { 3, 1 } };
 
    int N = sizeof(A) / sizeof(A[0]);
 
    // Function Call
    longestSubSequence(A, N);
 
    return 0;
}


Java
// Java program for the above approach
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, prthe 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.


Javascript


输出:
2

时间复杂度: O(2 N )
辅助空间: O(1)

高效方法:这个问题具有重叠子问题属性和最优子结构属性。因此,这个问题可以使用动态规划来解决。与其他典型的动态规划 ( DP ) 问题一样,可以通过构造一个存储子问题结果的临时数组来避免重新计算相同的子问题。

请按照以下步骤解决此问题:

  • 初始化一个dp[]数组,其中dp[i]存储可以使用索引i 之前的元素形成的最长子序列的长度。
  • 使用变量i在范围[0, N-1] 上迭代:  
    • 基本情况:将dp[i]更新为1。
    • 使用变量j在范围[0, i – 1] 上迭代:
      •  如果A [j]的。首先是小于A [I]。第一A [j]的。第二大于A [I]。第二,然后更新DP [I]作为最大DP [i]DP [j] + 1。
    • 最后,打印dp[N-1]

下面是上述方法的实现:

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 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 A[] = { { 1, 2 },
                           { 2, 2 },
                           { 3, 1 } };
 
    int N = sizeof(A) / sizeof(A[0]);
 
    // Function Call
    longestSubSequence(A, N);
 
    return 0;
}

Java

// Java program for the above approach
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

蟒蛇3

# 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, prthe 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.

Javascript


输出:
2

时间复杂度: O(N 2 )
辅助空间: O(N)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程