Search code examples
javaalgorithmbufferedreaderminmax

Non-empty subsets from HackerEarth exercises


Actually, I am doing an exercise from HackerEarth.

The exercise is pretty simple: I have to use a min-max algorithm but I have some struggles when I use the readLine method from the variable BufferReader.

I cannot figure out why but my min variable for an iteration keep the Integer.MAX_VALUE.

Code

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

class TestClass {
    public static void main(String args[] ) throws Exception {
        //BufferedReader
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int T = Integer.parseInt(br.readLine());
        int N = Integer.parseInt(br.readLine()); 
        
        while (T-- >= 0) {
            String[] line = br.readLine().trim().split("\\s");
            int min = Integer.MAX_VALUE;
            for (int i = 0; i < line.length - 1; i++) {
                min = Math.min(min, Integer.parseInt(line[i]));
            }

            System.out.println(min);
        }

        
    }
}

Output

1
2147483647
2

Solution

  • I've made many corrections to your code.

    1. You are not reading every N of every test case, you only read it once. You have to put it inside the while loop.
    2. Method trim is unnecessary because inputs from the problems are always in the right manner.
    3. Use > not >= when comparing using array lengths or the number of test cases, because it will iterate once more even if the index is already beyond the array's capacity or 0.
    public static void main(String args[] ) throws Exception {
        //BufferedReader
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int T = Integer.parseInt(br.readLine());
            
        while (T-- > 0) {
            br.readLine(); // to read N
            String[] line = br.readLine().split(" ");
            int min = Integer.MAX_VALUE;
            for (int i = 0; i < line.length; i++) {
                min = Math.min(min, Integer.parseInt(line[i]));
            }
    
            System.out.println(min);
        }
    }