using dynamic programming to eliminate repeated compare