DeepL interview question

What is the most optimal algorithm for this problem, and why