// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Initialize dp and KMP array
int dp[6][6][6];
int KMPArray[2];
// Length of the given sequence[]
int m;
// Function to find the max-length
// subsequence that does not have
// subarray sequence[]
int findSubsequence(int a[], int sequence[], int i,
int prev, int k, int al, int sl)
{
// Stores the subsequence
// explored so far
if (k == m)
return INT_MIN;
// Base Case
if (i == al)
return 0;
// Using memoization to
// avoid re-computation
if (prev != -1 && dp[i][prev][k] != -1) {
return dp[i][prev][k];
}
int include = 0;
if (prev == -1 || a[i] >= a[prev]) {
int k2 = k;
// Using KMP array to find
// corresponding index in arr1[]
while (k2 > 0
&& a[i] != sequence[k2])
k2 = KMPArray[k2 - 1];
// Incrementing k2 as we are
// including this element in
// the subsequence
if (a[i] == sequence[k2])
k2++;
// Possible answer for
// current state
include = 1
+ findSubsequence(
a, sequence,
i + 1, i, k2, al, sl);
}
// Maximum answer for
// current state
int ans = max(
include, findSubsequence(
a, sequence,
i + 1, prev, k, al, sl));
// Memoizing the answer for
// the corresponding state
if (prev != -1) {
dp[i][prev][k] = ans;
}
// Return the answer for
// current state
return ans;
}
// Function that generate KMP Array
void fillKMPArray(int pattern[])
{
// Previous longest prefix suffix
int j = 0;
int i = 1;
// KMPArray[0] is a always 0
KMPArray[0] = 0;
// The loop calculates KMPArray[i]
// for i = 1 to M - 1
while (i < m) {
// If current character is
// same
if (pattern[i] == pattern[j]) {
j++;
// Update the KMP array
KMPArray[i] = j;
i++;
}
// Otherwise
else {
// Update the KMP array
if (j != 0)
j = KMPArray[j - 1];
else {
KMPArray[i] = j;
i++;
}
}
}
}
// Function to print the maximum
// possible length
void printAnswer(int a[], int sequence[], int al, int sl)
{
// Length of the given sequence
m = sl;
// Generate KMP array
fillKMPArray(sequence);
// Initialize the states to -1
memset(dp, -1, sizeof(dp));
// Get answer
int ans = findSubsequence(a, sequence, 0, -1, 0, al, sl);
// Print answer
cout << ((ans < 0) ? 0 : ans) << endl;
}
// Driver code
int main()
{
// Given array
int arr[] = { 5, 3, 9, 3, 4, 7 };
// Give arr1
int arr1[] = { 3, 4 };
// Function Call
printAnswer(arr, arr1, 6, 2);
return 0;
}
// This code is contributed by divyeshrabadiya07.