Safe Grid Search with Optimal Complexity