Let’s first look at the n^2 algorithm:
dp[0] = 1; for( int i = 1; i < len; i++ ) { dp[i] = 1; for( int j = 0; j < i; j++ ) { if( array[i] > array[j] ) { if( dp[i] < dp[j]+1 ) { dp[i] = dp[j]+1; } } } }
Now the improvement happens at the second loop, basically, you can improve the speed by using binary search. Besides the array dp[], let’s have another array c[], c is pretty special, c[i] means: the minimum value of the last element of the longest increasing sequence whose length is i.
sz = 1; c[1] = array[0]; /*at this point, the minimum value of the last element of the size 1 increasing sequence must be array[0]*/ dp[0] = 1; for( int i = 1; i < len; i++ ) { if( array[i] < c[1] ) { c[1] = array[i]; /*you have to update the minimum value right now*/ dp[i] = 1; } else if( array[i] > c[sz] ) { c[sz+1] = array[i]; dp[i] = sz+1; sz++; } else { int k = binary_search( c, sz, array[i] ); /*you want to find k so that c[k-1]<array[i]<c[k]*/ c[k] = array[i]; dp[i] = k; } }