We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
From your profile, I understand you prefer coding in Java, so I presume you are calling "Scanner.nextInt" to read one integer at a time from STDIN. However, an optimal solution is to read the entire line as a string via "BufferedReader.readLine", split the string by whitespace, and then parse all "N" integers into an array. You may compare the execution time of reading 100 thousand integers from STDIN with the following two solutions to see that Solution 2 is about 4 times faster than Solution 1. (Please note: I have an extremely-optimized Solution 3 which is about 10 times faster than Solution 1.)
Solution 1
in = Scanner(System.in);
int[] A = new int[N];
for(int i = 0; i < N; i++)
A[i] = in.nextInt();
Solution 2
in = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(in.readLine());
int[] A = new int[N];
int i = 0;
for(String integer: in.readLine().split(" "))
A[i++] = Integer.parseInt(integer);
Side Note
For testing purposes, you may use the following implementation to generate 100,000 random integers from -10,000 to 10,000. Good Luck!
Random Number Generation
random = new java.util.Random();
int maximum = 10_000;
int minimum = -10_000;
int N = 100_000;
System.out.println(N);
random.ints(minimum, maximum+1).limit(N).forEach(i->System.out.format("%d ", i));
System.out.println();
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
The Maximum Subarray
You are viewing a single comment's thread. Return to all comments →
From your profile, I understand you prefer coding in Java, so I presume you are calling "Scanner.nextInt" to read one integer at a time from STDIN. However, an optimal solution is to read the entire line as a string via "BufferedReader.readLine", split the string by whitespace, and then parse all "N" integers into an array. You may compare the execution time of reading 100 thousand integers from STDIN with the following two solutions to see that Solution 2 is about 4 times faster than Solution 1. (Please note: I have an extremely-optimized Solution 3 which is about 10 times faster than Solution 1.)
Solution 1
Solution 2
Side Note
For testing purposes, you may use the following implementation to generate 100,000 random integers from -10,000 to 10,000. Good Luck!
Random Number Generation