alternative solution to minimumTotal, using only linear extra space