possible java solution; time limit exceeded