On optimal heating and cooling strategies for melting and freezing