Optimal Purification of a Spin Ensemble by Quantum-Algorithmic Feedback