Some optimization to problem 1