Optimal local implementation of nonlocal quantum gates