Simple but (I think) complete solution

You can check the code comments for more details about the used approach.