Correct algorithm