1

Basically I need to find the 2nd maximum number in a array.

Suppose the size of the array is 5 and elements are user-inputed. Here's my solution:

class Main {
    public static void main(String[] args) {
        int q = 0;
        Scanner sc = new Scanner(System.in);
        int[] arr = new int[5];
        for (int i = 0; i < 5; i++) {
            arr[i] = sc.nextInt();
        }
        System.out.println(getSecondLargest(arr, 5));
    }

    public static int getSecondLargest(int[] a, int total) {
        int temp;
        for (int i = 0; i < total; i++) {
            for (int j = i + 1; j < total; j++) {
                if (a[i] == a[j]) {
                    return a[i];
                }
                if (a[i] > a[j]) {
                    temp = a[i];
                    a[i] = a[j];
                    a[j] = temp;
                }
            }
        }
        return a[total - 2];
    }
}

Everything works but it fails when the input has the multiple duplicates values of the maximum number. For eg - 5 5 5 4 3 it needs to give 4 as output but it returns 5 as output.

I also tried to simplify code since size is already mentioned:

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

public class Main {
    public static void main(String[] args) {
        int q = 0;
        Scanner sc = new Scanner(System.in);
        int[] arr = new int[5];
        for (int i = 0; i < 5; i++) {
            arr[i] = sc.nextInt();
        }
        print2largest(arr, 5);
    }

    static void print2largest(int arr[], 5) {
        Arrays.sort(arr);
        System.out.println(arr[3]);
    }
}

But for the above simplified code to work perfectly no duplicate values must be present in the array.

How to get 2nd maximum element in case of there are multiple duplicate values.

4
  • first, you can remove duplicate value from given array. Then you can easily get 2nd maximum element. It can be one of the approach. Commented May 23, 2021 at 16:14
  • It does not need to sort the array. just iterate over the array and check if the current value is smaller than a max value variable and bigger than a second max value variable. the initial value of the max value variable should be the largest possible value and the second max value variable should be the smallest possible value. finally, you should also check if the second max variable already contains its initial value or not. if yes, there is no second max value; if no, its containing value is the answer. Commented May 23, 2021 at 16:15
  • @Tausif never thought of that. thanks Commented May 23, 2021 at 16:22
  • Glad to see it helped you @JubinSaud Commented May 23, 2021 at 16:26

4 Answers 4

6

You can use Java-Stream to do this:

int[] arr = new int[] {3,5, 9, 7, 4, 12};

int secondLargest = Arrays.stream(arr)
        .boxed()
        .distinct()  // remove duplicates
        .sorted(Comparator.comparingInt(value -> (int) value).reversed())
        .skip(1)     // skip the first largest
        .findFirst()
        .get();

System.out.println(secondLargest);

Output:

9
Sign up to request clarification or add additional context in comments.

Comments

0

You can use a TreeSet with reverse comparing:

static void print2largest(int arr[]) {
    // Creates a TreeSet where, each time an element is added, will order it
    // with a reverse comparator (so the largest values will come first).
    // Since this is a set, it'll ignore duplicated elements.
    final Set<Integer> set = new TreeSet<>(Collections.reverseOrder());

    // Add all values from the input array to this set
    for (int value : arr) set.add(value);

    // Transforms the set into a list so we can get the second largest element
    final List<Integer> sortedValues = new ArrayList(set);

    // Returns the second largest element from this set
    System.out.println(sortedValues.get(1));
}

Comments

0

You can do two functions.(Simple algorithm)

 -First function:
 Remove duplicates.

-Second function:
Sort a given array, and return the element located in `[array.length-2]`.
Remember to check if `array.length >= 2`, else,( `array.length = 1` ), return 
array[0].

Comments

0

We can find the second largest number in an array in java by sorting the array and returning the 2nd largest number.

public class SecondLargestInArrayExample {
    public static int getSecondLargest(int[] a, int total) {
        int temp;
        for (int i = 0; i < total; i++) {
            for (int j = i + 1; j < total; j++) {
                if (a[i] > a[j]) {
                    temp = a[i];
                    a[i] = a[j];
                    a[j] = temp;
                }
            }
        }
        return a[total - 2];
    }

    public static void main(String args[]) {
        int a[] = {1, 2, 5, 6, 3, 2};
        int b[] = {44, 66, 99, 77, 33, 22, 55};
        System.out.println("Second Largest: " + getSecondLargest(a, 6));
        System.out.println("Second Largest: " + getSecondLargest(b, 7));
    }
}

Output:

Second Largest: 5
Second Largest: 77

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.