I am solving a programming challenge to find the length of longest increasing subsequence in a 2D NxN matrix. Both row and columns must increase in each element of a sequence (no need to be consecutive) . I solved it with Dynamic programming approach but it is O(N^4) and inefficient. However, there are many solutions in O(N^3). One such solution is:
scanf("%d", &N);
for(i = 1; i <= N; i++) {
for(j = 1; j <= N; j++) {
scanf("%d", &L[i][j]);
}
}
Answer = 0;
memset(maxLength,0,sizeof(maxLength));
for (i=1;i<=N;i++)
{
maxLength[1][i] = 1;
maxLength[i][1] = 1;
}
//
for (i=2;i<=N;i++)
{
memset(minValue,0,sizeof(minValue));
curLen = 1;
minValue[1] = L[i-1][1];
for (j=2;j<=N;j++)
{
for (p=1;p<i;p++)
{
tmpLen = maxLength[p][j-1];
if (minValue[tmpLen] == 0)
{
minValue[tmpLen] = L[p][j-1];
curLen = tmpLen;
}
else if (minValue[tmpLen]>L[p][j-1])
{
minValue[tmpLen] = L[p][j-1];
}
}
max = 1;
for (p=curLen;p>0;p--)
{
if (L[i][j]>=minValue[p])
{
max = p+1;
break;
}
}
maxLength[i][j] = max;
Answer = Answer>max?Answer:max;
}
}
// Print the answer to standard output(screen).
printf("%d\n", Answer);
Can someone explain how it works or any other O(N^3) approach ? i can't follow it at all :(.

