0

In competitive programming I used Integer instead of int but it got me TLE error Can you tell me why? Basically i have to just sort the array and traverse it. my code is here

    class Main
    {
    public static void main (String[] args) throws java.lang.Exception
    {
      Scanner sc = new Scanner(System.in);
      int scene = sc.nextInt();
      int j=1;
      while(j<=scene)
      {
        int need = sc.nextInt();
        int frnds = sc.nextInt();
        int arr[] = new int[frnds];
        for(int i=0;i<frnds;i++)
            arr[i] = sc.nextInt();
        Arrays.sort(arr);
        int count =0;
        System.out.println("Scenario #"+j+":");
        for(int i=frnds-1;i>=0;i--)
        {
            count++;
            need -= arr[i];
            if(need<=0) {
                System.out.println(count);
                break;
            }
        }
        if(need>0)
            System.out.println("impossible");
        System.out.println();
        j++;
    }
   }
  }
cs95
  • 379,657
  • 97
  • 704
  • 746
J_V
  • 3
  • 4
  • https://stackoverflow.com/questions/4624933/comparing-performance-of-int-and-integer – BackSlash Apr 10 '20 at 07:28
  • yeah thank u So basically if we compare normal operations like traversing then int will be faster than Integer. Am i right? – J_V Apr 10 '20 at 07:41
  • 1
    It is somewhat, but that's almost never the core problem. – chrylis -cautiouslyoptimistic- Apr 10 '20 at 07:45
  • Check https://stackoverflow.com/questions/21797573/why-is-scanner-slower-than-bufferedreader-when-reading-from-input and https://www.quora.com/Why-is-Scanner-so-much-slower-than-BufferedReader as well. – Arvind Kumar Avinash Apr 10 '20 at 07:55
  • I understand what you guys are trying to say that buffered reader is faster than Scanner.But in above given code I used Scanner but I submit two versions one with storing values in Integer array and one with int array .The code in which i used Integer gave me TLE. I wanted to know reason behind that and I think the above guys had given somewhat right answer that wrapper classes are slower than primitive data types. If I am wrong then please correct me. – J_V Apr 11 '20 at 08:17

1 Answers1

-1

In your example, you are using Scanner to read data from the input stream but its extremely slow, use BufferedReader instead. Example:

try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
     String line = reader.readLine();
     ....
} catch (IOException e) {
     e.printStackTrace();
}

That will speed up your execution time.

ish
  • 161
  • 7
  • @J_V I am unable to see how this answers the question you asked. The assertion that `Scanner` is 'extremely slow' is false, and the apparent assertion that this will speed up your code more than using `int` instead of `Integer` ditto. – user207421 Jul 07 '20 at 03:05