Longest Common Subsequence from reverse
int [ ] [ ] dpr = new int [ N + 2 ] [ M + 2 ] ; for ( int i = N ; i >= 1 ; i -- ) { for ( int j = M ; j >= 1 ; j -- ) { if ( A . charAt ( i - 1 ) == B . charAt ( j - 1 ) ) dpr [ i ] [ j ] = dpr [ i + 1 ] [ j + 1 ] + 1 ; else dpr [ i ] [ j ] = Math . max ( dpr [ i + 1 ] [ j ] , dpr [ i ] [ j + 1 ] ) ; } }