Help me in solving LARGESECOND problem

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

The problem with your code is this part:

int secondMax = arr[0];

Your code will output 4 instead of 3 because it doesn’t take into account that a[0] might be equal to the first maximum number.

Corrected Code:

import java.util.Arrays;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int t = scanner.nextInt();

        for (int i = 0; i < t; i++) {
            int n = scanner.nextInt();
            int[] arr = new int[n];

            for (int j = 0; j < n; j++) {
                arr[j] = scanner.nextInt();
            }

            Arrays.sort(arr);
            int idx = n - 2;
            while (arr[n - 1] == arr[idx]) {
                idx--;
            }

            System.out.println(arr[n - 1] + arr[idx]);
        }
    }
}

I simply sorted the array and till the second maximum isn’t equal to the first, I decrement the indext of it.

1 Like

Thanks mate!