Anda di halaman 1dari 4

LAB – 14

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;

for (int i = 1; i < n; i++)


{
temp = longestSeq(arr, i, max_ref);
if (arr[i-1] < arr[n-1] && res + 1 > 1)
max_ending_here = res + 1;
}
if (max_ref < max_ending_here)
max_ref = max_ending_here;
return max_ending_here;
}

Page | 80
SOURCE CODE:
#include<stdio.h>
#include<stdlib.h>

int longestSeq( int arr[], int n, int *max_ref)


{
if (n == 1)
return 1;

int res, max_ending_here = 1;


for (int i = 1; i < n; i++)
{
res = longestSeq(arr, i, max_ref);
if (arr[i-1] < arr[n-1] && res + 1 > max_ending_here)
max_ending_here = res + 1;
}
if (*max_ref < max_ending_here)
*max_ref = max_ending_here;
return max_ending_here;
}

int lis(int arr[], int n)


{
int max = 1;
longestSeq( arr, n, &max );
return max;
}

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)

Now, observe the recurrence:


f(n) = f(n-1) + f(n-2) + f(n-3) + ... + f(1)
where recursively f(n-1) = f(n-2) + f(n-3) + ... f(1)

Clearly, we can observe that f(n) = 2*f(n-1)


So our compact recurrence relation is f(n) = 2*f(n-1)

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)

Hence the complexity is exponential = 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

Anda mungkin juga menyukai