A dynamic array can be declared with its length equal to the maximum length of the increasing sequence. The ANS array will contain the longest ascending sequence.
int *ans=(int*)malloc(sizeof(int)*max);
A temporary variable is used to store the maximum length index in an array.
int index; int length; //used to fill array ANS in reverse order. for ( i = 0; i < n; i++ ) { if ( max < lis[i] ) { max = lis[i]; index=i; } } length=max; ans[length-1]=arr[index]; //filling array from the last //last element will be the greatest element length--; while(index>0) { for(i=index-1;i>=0;i--) { if(lis[i]+1==lis[index] && arr[i]<arr[index]) { ans[length-1]=arr[i]; index=i; length--; break; } } } for(i=0;i<max;i++) { printf("%d",ans[i]); }
Here the complexity is O (n), not O (n2), even if it can use two loops, since we change the index value by i whenever a block is entered.
source share