Professional Documents
Culture Documents
22##
22##
AIM:
To implement longest integer sequence.
SOFTWARE USED:
Ubuntu 16.04 in VM Virtual Box.
PSEUDOCODE:
algo longestSeq( int arr, int n, int max_ref)
{
if (n == 1)
return 1;
Page | 80
SOURCE CODE:
#include<stdio.h>
#include<stdlib.h>
Page | 81
int main()
{
int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 };
int n = sizeof(arr)/sizeof(arr[0]);
printf("Length of the longest int sequence is %dn", lis(arr, n));
return 0;
}
ANALYSIS:
Let the complexity of the solution without dynamic programming for an input size n = f(n)
f(n) = 2*f(n-1)
f(n-1) = 2*f(n-2)
...
f(2) = 2*f(1)
f(1) = 2*f(0)
Among the above equations, multiply the ith equation by 2(i-1) and then add all the
equations. We clearly then have f(n) = (2n)*f(0) = O(2n)
Page | 82
Now let's look at what happens when we use dynamic programming. When we use DP,
we are saving f(n) once we compute it, so that we don't compute it ever again in the
recursion. That leaves us with:
f(n) = f(n-1) + f(n-2) + ... f(1)
but this time when the recursive call of f(n-1) computes f(n-2), f(n-3), etc. then we don't
have to recompute it while calculating f(n).
So now, we get f(n) = n + (n-1) + (n-2) + ... 1 which is O(n2).
OUTPUT:
Length of the longest in sequence is 5.
Page | 83