I just started attempting SPOJ problems. And I'm aware of Java using more memory and time compared to most of the other languages. But even some of the solutions in Java have better results than my accepted code. And it hurts!
Here is my accepted code for FASHION with TIME: 0.41 and MEM: 4284M.The best solution in Java for the same question has TIME: 0.04 and MEM: 1398M.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int i = 0;
Scanner sc = new Scanner(System.in);
int testCases = sc.nextInt();
while (testCases > 0) {
int modelsWithMe = sc.nextInt();
int[] men = new int[modelsWithMe];
int[] women = new int[modelsWithMe];
int hotnessSum = 0;
for (i = 0; i < modelsWithMe; i++) {
men[i] = sc.nextInt();
}
for (i = 0; i < modelsWithMe; i++) {
women[i] = sc.nextInt();
}
Arrays.sort(men);
Arrays.sort(women);
for (i = 0; i < modelsWithMe; i++) {
hotnessSum = hotnessSum + men[i] * women[i];
}
System.out.println(hotnessSum);
testCases--;
}
}
}
I did see a few questions on performance, such as this and this. I am doing a few of it and some are not applicable for this solution's point of view. Here, maybe, I can read the entire line at once and split the string instead of calling nextInt
each time and reduce I/O operations. What else can I do to reach the level of efficiency and speed as that of top answers? Best practices may be?