0
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

class Main {

    public static void main(String[] args) throws NumberFormatException, IOException {
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));        
        int t = Integer.parseInt(input.readLine());

        for (int i = 0; i < t; i++) {
            String[] arrayData = input.readLine().split(" ");
            int[] cardsi = new int[arrayData.length];
            int e = 0;

            for(int a = 0; a < arrayData.length; a++){
                cardsi[e] = Integer.parseInt(arrayData[a]);
                e++;
            }

            int X = cardsi[0];
            int N = cardsi[1];
            long count = 0;

            for (int j = 2; j < cardsi.length; j++) {
                for (int l = 3; l <= (cardsi.length - 1); l++) {
                    if ((cardsi[j] + cardsi[l]) == X &&(j != l)) {
                        count++;
                    }
                }
            }
            System.out.println((i + 1) + ". " + count);
        }

    }
}

Time limit exceeded error is appearing upon submitting this LCPC12F problem on spoj.. what might be a solution? Is scanner a major trouble for such error to appear?

Michael
  • 3,093
  • 7
  • 39
  • 83
DCodes
  • 789
  • 1
  • 11
  • 27
  • You ask about Scanner (which you should NOT use) but you're correctly using a BufferedReader instead. What's the complexity of your algorithm? – k_ssb Jun 19 '18 at 13:18
  • Your solution is `O(N^2)` which is too slow for the given bound of `N <= 10^5`. You need a more clever algorithm. – k_ssb Jun 19 '18 at 13:21
  • This is a simple variation of the 2-sum problem. See https://www.programcreek.com/2012/12/leetcode-solution-of-two-sum-in-java/, you should either sort the array for `O(N log N)` or use hashing to get `O(N)`. – k_ssb Jun 19 '18 at 13:24

1 Answers1

0

Have you ever run those codes on IDE?

When I give the number to t element then arrayData (in this case, we should enter int type not String, because of the java.lang.NumberFormatException), it shows Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 and int N = cardsi[1]; is the main problem on your code I think. This is because String[] arrayData = input.readLine().split(" "); size is 1 so you do not have cardsi[1] element on your int array

jundev
  • 159
  • 1
  • 1
  • 11