The algorithm can be optimized further.