// C program to find longest increasing subsequence using
// Memoization
#include <stdio.h>
#include <string.h>
// Function to return the maximum of two integers
int max(int a, int b) { return (a > b) ? a : b; }
// Function to find the length of the Longest Increasing
// Subsequence (LIS) using memoization
int lisMemoization(int arr[], int n, int* memo)
{
// If the value is already computed, return it
if (memo[n] != -1)
return memo[n];
// Initialize max_ending_here to 1 for the current
// element
int res, max_ending_here = 1;
// Recursively find the LIS ending at each element
// before arr[n-1]
for (int i = 1; i < n; i++) {
res = lisMemoization(arr, i, memo);
// If arr[i-1] is smaller than arr[n-1], and
// including arr[n-1] results in a longer
// subsequence
if (arr[i - 1] < arr[n - 1]
&& res + 1 > max_ending_here)
max_ending_here = res + 1;
}
// Store the result in memo array and return it
return memo[n] = max_ending_here;
}
// Function to find the length of the Longest Increasing
// Subsequence (LIS) in an array
int lis(int arr[], int n)
{
// Memoization array
int memo[n + 1];
// Initialize memo array with -1
memset(memo, -1, sizeof(memo));
// Initialize the maximum LIS length
int maxLength = 1;
// Compute the LIS length for each element in the array
for (int i = 1; i <= n; i++)
maxLength
= max(maxLength, lisMemoization(arr, i, memo));
// Return the maximum LIS length found
return maxLength;
}
int main()
{
// Input array
int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60, 80 };
// Size of the array
int n = sizeof(arr) / sizeof(arr[0]);
// Print the length of the Longest Increasing
// Subsequence (LIS)
printf("Length of LIS is %d\n", lis(arr, n));
return 0;
}