Pergunta de entrevista da empresa Microsoft

Find an efficient algorithm for this problem