Counting athletes whose height is in a given range Challenge: Sort by growth


  Input
  
  
  The first line of each query contains one number n (1 ≤ n ≤ 20000) - the number of members in corresponding delegation.
  The second line contains n unsorted integers - the heights of athletes in centimeters.  Every height is at least 150 cm, and no greater than 250 cm.
  The third line contains a and b: the lower and upper height limits.
  
  
  Output
  
  For each query print the count on a separate line.
  
  Time limit: 2 seconds
  Memory limit: 256 MiB


My program works correctly, but I have a running time of 3020 ms.

 import java.io.PrintWriter;
 import java.util.Scanner;

 public class OlimpGames {
   public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
     PrintWriter out = new PrintWriter(System.out, true);
      {
       while (in.hasNextInt()) {
        int n = in.nextInt();

        int heigh[] = new int[100];
        for (int i = 0; i &lt; n; i++) {
            heigh[in.nextInt() - 150]++;
        }
        int a = in.nextInt();
        int b = in.nextInt();

        int an = 0;
        for (int i = a - 150; i &lt;= b - 150; i++) {
            an = an + heigh[i];
        }
        System.out.println(an);
       }
      }
  }
}
Your code and algorithm seem pretty optimal for the problem.

A minor nit-pick, the PrintWriter "out" is not being used.  (The braces immediately following are unnecessary, but wouldn't affect performance.)

There are only 2 tiny things which might help:

1) In each loop, you're allocating a new int[] array.  If you didn't do this, you would need to call Arrays.fill() to zero out the array each time.  I doubt there would be much difference as allocations of this type are pretty fast.

2) The bigger possibility is I/O performance on the output.  When fine-tuning to meet a time constraint, I/O might make the difference.  Instead of calling System.out.println, try using a StringBuilder and appending the output.  Then, after the main loop, do a single output operation on the resultant string.

Also, one final tip.  The linked problem statement indicates that none are less than 150 or greater than 250.  If you get input with 250, you will get an array bounds exception.  You need an array of size 101.