Bending Spoons interview question

An algorithm design programming question, including a final step with optimisation + explanation of my solution.