My issue
My code fails at a test case that inputs 200 elements in an array and only contains 1’s and 2’s. So the correct answer should’ve been 3 (the output by my code) but the right answer according to the test case is 4. Can somebody help me with this?
My code
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for(int i=0; i<t; i++){
int n = sc.nextInt();
int[] arr = new int[n];
for(int j=0; j<n; j++){
arr[j] = sc.nextInt();
}
int max = arr[0];
for(int j=1; j<n; j++){
if(arr[j] > max){
max = arr[j];
}
}
int secondMax = arr[0];
for(int j=1; j<n; j++){
if(arr[j] > secondMax && arr[j] != max){
secondMax = arr[j];
}
}
System.out.println(max+secondMax);
}
}
}
Learning course: Arrays using Java
Problem Link: CodeChef: Practical coding for everyone