Optimal conditions for the extension of the mean curvature flow