Amazon Interview Question
Software Engineer / Developerswell lcs with same one in sorted order, find the lcs of array1 with array1 sorted...this problem is called longest increasing subsequence.....there is an standalone solution as well..with above DP:
working code in O(n2)
/* To find longest monotonically increasing subsequence */
int a[] = { 1,4,6,2,3,0,5};
int lcs[100], p[100];
//initialize
int size = sizeof(a)/sizeof(a[0]);
for(int i=0; i < size; ++i)
{
lcs[i]=1; p[i] = -1;
}
for(int i=0; i < size; ++i)
for(int j=0; j < i; ++j)
{
if(a[i] > a[j])
{
//find max of lcs[i], lcs[j]+1
if( lcs[j]+1 > lcs[i] )
{
lcs[i] = lcs[j] + 1;
p[i] = j;
}
}
}
int max=lcs[0], maxInd=0;
for( int i=1; i < size; ++i)
if( lcs[i] > max )
{
max = lcs[i];
maxInd = i;
}
while( true )
{
cout << a[maxInd] << endl;
maxInd = p[maxInd];
if( maxInd == -1 )
break;
}
O(n) Solution
public class Amazon9 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int sIndex=0;
int eIndex=0;
int i=0;
int j=0;
int [] a = {8,6,5,1,9,3,7,4,2,10};
int max=1;
int count=1;
while(j<a.length)
{
j++;
if(j<a.length && a[j]>=a[j-1])
{
count++;
}
else
{
if(count>max)
{
max=count;
sIndex=i;
eIndex=j-1;
}
i=j;
count=1;
}
}
System.out.println("Sequence Size:"+max);
for(i=sIndex;i<=eIndex;i++)
System.out.print(a[i]+",");
}
}
Use patience sort :
en.wikipedia.org/wiki/Patience_sorting
Nice animation at :
wordaligned.org/articles/patience-sort
I think patience sort is good but I'm getting a problem:
Suppose I/P array is {8,6,5,1,9,3,7,4,2,10}
first 8 is kept on a new pile
then 6, as it is smaller than 8 is again kept on a new pile
then 5 on a new pile
then 1 on a new pile
then 9 is kept over 8, as 9 is greater than 8
then 3 is put over 1
then 7 is put over 6
then 4 is put over 3
then 2 on a new pile
and now, what about 10?
where it should be kept?
over 9 or 7 or 5 or 4 or 2?
Now I think we can check for the top value in case of collision and keep on the pile having greatest value of the top so that we get longest sequece........
If anyone can help me out whether my idea is right or wrong?
int main()
{
int a[] = { 1,4,6,2,3,0,5};
int lcs[100], p[100];
int i=0,j=0, maxIndex=0;
//initialize
int size = sizeof(a)/sizeof(a[0]);
for(i=0; i < size; ++i)
{
lcs[i]=1; p[i] = -1;
}
for(i=1; i< size; i++ )
{
for(j = i-1; j>=0; j-- )
{
if( (a[j] < a[i] ) && (lcs[i] < (lcs[j] + 1)))
{
lcs[i] = lcs[j]+1;
p[i] = j;
if( lcs[maxIndex] < lcs[i] )
maxIndex = i;
}
}
}
i = maxIndex;
do
{
cout<<a[i]<<",";
i = p[i];
}while(i!=-1);
return 0;
}
Time complexity O(n2)
How will 2 be handelled?
- Tarun Phaugat March 22, 2010output can be 1,3,2,10
instead of 1,3,4,10