Solution for MaxPrefix task