Problem :
standard input/output: 2s/128000 kB
You are given a chessboard of size N x N, where the top left square is black. Each square contains a value. Find the sum of values of all black square and all white squares.
1 <= N <= 1000
Solution 1:
Now when I am using Scanner
to take the input, it is throwing memory limit exceeded
for one test case
Scanner sc = new Scanner(System.in);
long n = sc.nextLong();
long wsum = 0;
long bsum = 0;
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
if((i+j)%2 != 0 ) {
wsum = wsum + sc.nextLong();
}
else {
bsum = bsum + sc.nextLong();
}
}
}
Solution 2: When I am using the BufferedReader
all test cases are passing
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(read.readLine());
int mat[][] = new int[N][N];
for(int i = 0; i < N; i++){
String str[] = read.readLine().trim().split(" ");
for(int j = 0; j < N; j++)
mat[i][j] = Integer.parseInt(str[j]);
}
long sum =0, sum1 = 0;
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
if((i+j)%2 == 0)
sum += mat[i][j];
else sum1 += mat[i][j];
}
}
Now I know BufferedReader
is efficient while reading file but that should throw time limit exceeded
.
I would like to understand how BufferedReader
is making this program more memory efficient as compared to Scanner
class.
question from:
https://stackoverflow.com/questions/65903521/memory-limit-exceeded-when-using-java-scanner 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…