TLE, but correct solution

C++ would pass this.. Not sure how to optimize on Java.