changed algorithm to min max