I was trying to solve a challenge. The execution time should not exceed 5s, but for some value my code took longer. I want to know if I can optimize my code for performance.
public class Solution {
int n;long k;int count=0;
public static void main(String[] args) {
new Solution().readInput();
}
public void readInput(){
try {
BufferedReader k=new BufferedReader(new InputStreamReader(new FileInputStream("/home/tittanium/NetBeansProjects/HackerRank/src/input.txt")));
parseNK(k.readLine());
readAndParse(k.readLine());
System.out.println(count);
} catch (IOException ex) {
Logger.getLogger(Solution.class.getName()).log(Level.SEVERE, null, ex);
}
}
int cities[];
public void readAndParse(String line){
int i1=0;
cities=new int[n];
StringTokenizer st = new StringTokenizer(line," ");
while (st.hasMoreElements()) {
cities[i1]=Integer.parseInt(st.nextToken());
i1++;
}
for(int i=0;i<n;i++){
final int x=i;
new Runnable() {
@Override
public void run() {
for(int j=x;j<n;j++){
final int a=cities[x];
final int b=cities[j];
count = (a>b ? a-b : b-a) == k ? count+1 : count;
}
}
}.run();
}
}
public void parseNK(String line){
n= Integer.parseInt(line.split(" ")[0]);
k= Integer.parseInt(line.split(" ")[1]);
}
}
This question is trying to solve a problem. I want to know if any changes can be made to make the program run faster. This is what I am trying to complete. challenge