Source: Codeforces 2002C
Design an algorithm to solve the problem.
Analyse the time complexity of your algorithm and estimate its running time.