Optimized cavity-mediated dispersive two-qubit gates between spin qubits