Yet another solution with quadratic running time.