CCO 2021 problem 6

problem link:
https://dmoj.ca/problem/cco21p6 or https://oj.uz/problem/view/CCO21_day2problem3

I’ve been stuck on this problem for quite a long time.
I saw others’ code and it looks like some sort of greedy, but I don’t really understand it.

Thanks.