Added optimizations

This version times out for the case 4000 3 4 5