improved implementation of minmax