This may be a very classical problem of finding longest non-decreasing subsequence in O(nlogn). Just to revise, length of longest non-decreasing subsequence in array A={2 4 2 3 3 5 1} is 5 {2 2 3 3 5}.
However, After countless efforts I fail to understand where my implementation of the algorithm is failing. I've read and implementing the algorithm described Here and Here with only a little change of "=" sign to allow equal elements in O(nlogn) implementation of longest increasing subsequence. I'm attempting this problem where trivial O(n^2) approach (which is correct as the solution got accepted) and O(nlogn) approach are giving different solutions (which I inferred by assert statements) which proves that something is wrong for sure with my O(nlogn) implementation.
My O(nlogn) implementation is as follows:
/* Array LNDS will be used for finding
longest non-decreasing subsequence in array A of size n */
int LNDS[n],len=1,x; // len will be storing the required length
fill(LNDS,LNDS+n,0);
LNDS[0]=A[0];
for(int i=1; i<n; i++)
{
x=LNDS[len-1];
if(A[i]<LNDS[0])
LNDS[0]=A[i];
else if(A[i]>=x) // "=" sign to allow equal elements
LNDS[len++]=A[i];
else
{
l=0;
r=len-1;
while(r-l>1) // binary search for finding lower bound for A[i] in LNDS
{
m=(l+r)/2;
if(LNDS[m]>=A[i]) r=m;
else l=m;
}
LNDS[r]=A[i];
}
}
return len;