Cartons of milk

CodeForces - 767D