Functionally, your code is very similar to my own AC Pascal, so I expect this is a just a Java-is-relatively-slow TLE rather than using a wrong algorithm one. How efficient is the Scanner class at reading and parsing the input? There could be 100,000 numbers to read, could they be read any faster?