I need help to create an algorithm for this example

Check this thread: