When trying to come up with an algorithm for such a scenario, dividing it up into possible cases would help. Creating one algorithm that can handle dynamic sizes of (insert something here) is often...