Improved algorithm for problem #5