What could be the reasons for Time Limit Exceeding problem in a program??

Please tell me the reason for the time limit exceeding problem and way that i can reduce it. The following is one of the code that i am facing this issue, but the same logic which i wrote in C doesn’t make that problem.
This is Java Code:

import java.util.;
import java.lang.
import java.io.*;

class Codechef
public static void main (String[] args) throws java.lang.Exception
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
int n = sc.nextInt();
int count = 0;
long sum = 0;

while(t != 0)
	sum = sc.nextLong();


I tested this code in the IDE provided by Code Chef with the inputs given in the problem statement but when i submit the same, it giving that Time Limit Exceeded.
Kindly tell me the reason.

This link Provides you with @admin’s explanation of Time Limit Exceeded


1 Like

In java Scanner is slow for reading inputs/outputs, use some faster input procedure. For example you can use BufferedReader or some other custom classes.

See sample using BufferedReader here. For BufferedReader multiple integers/longs in the same line, read using readLine() and use StringTokenizer or String.split methods.

See your same code ACcepted here using faster I/O. :smiley:

1 Like