Improved the algorithm