another algorithm (Time Limit Exceeded)