Monday, May 16, 2022

[Solved] How to Find 2 Largest Number from Integer Array in Java with Example

Hello guys, I have been sharing a lot of Programming interview questions and coding problems to learn programming better which is appreciated by you guys. In this post, I have come with other simple programming problems for Java beginners. I love to share short programming problems because they help in developing programming sense. Many people will argue against simple problems like prime numbers, palindrome, and factorial, but I really find them useful, especially for beginners. A beginner is far away to solve a complex data structure problem or even more complex problems like those that appear in TopCoder or other programming sites. Programmers learn gradually and they need the joy of doing something and seeing results much quicker than any other. Small success motivates them.

Anyway, here is our problem statement, you need to write a Java program to find the top two maximum numbers in the given array. You can not use any sorting functions and you should iterate the array only once. The use of any kind of collection class like TreeSet or LinkedHashSet is also not allowed.

For example, if the given integer array is [20, 34, 21, 87, 92, 2147483647] then the first maximum is 2147483647 and the second maximum is 92. Bonus points are for those, who can also write JUnit test cases, more test scenarios, more points.

Few more bonus points for those who can write code to deal with a really large array, something which may not entirely fit on memory. Btw, a good knowledge of fundamental data structure like an array is very important for every programmer.

If you need to brush up your algorithms skills or want to learn data structure in depth then and need a course then  I highly recommend Data Structure and  Algorithms in Java: Deep Dive on Udemy. It's both comprehensive and enjoyable and also very affordable. You can buy it for just $10 on Udemy sale.



How to Find Top Two Maximum Numbers from Integer Array

Here is our sample Java program, It solves the problem following the given problem statement and under constraints states. For example, it doesn't use any sorting algorithm like bubble sort or quicksort, or Collections.sort() method.

As I said before,  this kind of program is a good exercise for mastering basic building blocks of any programming language like loops, if-else block, and learning relational operators like less than (<) and greater than (>).

It takes advantage of the if-else control statement to solve this problem. All we do is start with two variables as max1 and max2 and initialized them with Integer.MIN_VALUE, which is the limit of minimum value.

Now we iterate through the array and compare each number against these two numbers, if the current number is greater than max1 then max1 = number, and max2 = max1. Otherwise if it only greater than max2 then we only update max2 with the current number.

At the end of the iteration, max1 and max2 point to the top two numbers from a given array. You see the problem solved without any utility class or third-party library. Though, if you are new to Java and not very familiar with the conditional statements in Java like the if-else-if block or switch statement then also recommend you check out a comprehensive Java course like The Complete Java MasterClass to learn Java better. This is also very affordable and you can buy in just $9.99 on crazy Udemy sales.

How to Calculate Top Two Maximum Number from Integer array in Java



Java Program To Find Top Two Numbers from Integer Array

Now, without wasting any more of your time, here is our complete code example which you can copy-paste in Eclipse or your favorite IDE and run it. You can also save this code in a file called TopTwoMaximum.java and run it from the command prompt.


import java.util.Arrays;
/**
 * Java program to find top two maximum numbers from an integer array. 
 * 
 * @author http://java67.blogspot.com
 */
public class TopTwoMaximum{

    public static void main(String args[]) {
        topTwo(new int[]{20, 34, 21, 87, 92, Integer.MAX_VALUE});
        topTwo(new int[]{0, Integer.MIN_VALUE, -2});
        topTwo(new int[]{Integer.MAX_VALUE, 0, Integer.MAX_VALUE});
        topTwo(new int[]{1, 1, 0});
    }

    public static void topTwo(int[] numbers) {
        int max1 = Integer.MIN_VALUE;
        int max2 = Integer.MIN_VALUE;
        for (int number : numbers) {
            if (number > max1) {
                max2 = max1;
                max1 = number;
            } else if (number > max2) {
                max2 = number;
            }
        }

        System.out.println("Given integer array : " 
                               + Arrays.toString(numbers));
        System.out.println("First maximum number is : " + max1);
        System.out.println("Second maximum number is : " + max2);
    }

}

Output:
Given integer array : [20, 34, 21, 87, 92, 2147483647]
First maximum number is : 2147483647
Second maximum number is : 92
Given integer array : [0, -2147483648, -2]
First maximum number is : 0
Second maximum number is : -2
Given integer array : [2147483647, 0, 2147483647]
First maximum number is : 2147483647
Second maximum number is : 2147483647
Given integer array : [1, 1, 0]
First maximum number is : 1
Second maximum number is : 1

From the output, you can see that our method the topTwo(int[] numbers) is working properly for different sets of inputs. I have chosen the main method over the JUnit test for testing my code, which is quick and dirty.

JUnit testing provides you more options and a better framework to write test cases. If you don't know how to write a JUnit test case, see that link. It explains that in detail.

That's all on how to find two maximum from integer array in Java. How about extending it further and finding the top three numbers from the integer array? Can you do that without any help? Once you have done that,

You can probably try finding the top three minimum numbers from the array. For example, if the given array is [11, 2, 5, 4] then the top three minimum numbers are 2, 4, and 5. You can even extend this logic even to find the largest and smallest number in an array, as shown in that example



Other  Programming Interview Questions and Articles  for Java developers
  • How to reverse an array in place in Java? (solution)
  • Top 5 Courses to learn Data Structure and Algorithms (courses)
  • 10 Free Courses to learn Data Structure and Algorithms (free courses)
  • How to find one missing number in a sorted array? (solution)
  • How to remove an element from an array in Java? (solution)
  • How to check if an array contains a particular value? (solution)
  • Top 5 Books to learn Data Structure and Algorithms (Books)
  • How to find all pairs in an array whose sum is equal to k (solution)
  • Top 5 Courses to learn Dynamic Programming for Interviews (courses)
  • How to find the largest and smallest number in an array without sorting? (solution)
  • How do find the top 2 numbers from a given array? (solution)
  • Top 30 linked list coding interview questions (see here)
  • 25 Software Design Interview Questions for Java developer (questions)
  • 10 Free Data Structure and Algorithm Courses for Programmers (courses)
  • 100+ Data Structure Coding Problems from Interviews (questions)
  • How to sort an array using bubble sort in Java? (solution)
  • Top 50 Java Programs from Coding Interviews (see here)
  • 5 Free Data Structure and Algorithms Courses for Programmers (courses)
  • 10 Algorithms Books Every Programmer Should Read (books)
  • How to find duplicates from an unsorted array in Java? (solution)
  • How to remove duplicates from an array in Java? (solution)

Thanks for reading this article so far. If you like this coding tutorial then please share it with your friends and colleagues. If you have any questions or doubt then please let us know and I'll try to find an answer for you. As always suggestions, comments, innovative and better answers are most welcome.

P. S. - If you are looking for some Free Algorithms courses to improve your understanding of Data Structure and Algorithms, then you should also check the Data Structure in Java free course on Udemy. It's completely free and all you need to do is create a free Udemy account to enroll in this course.

19 comments:

  1. public static void topTwo2(int[] numbers) {
    Arrays.sort(numbers);

    System.out.println(numbers[numbers.length-2]);
    System.out.println(numbers[numbers.length-1]);

    }

    ReplyDelete
    Replies
    1. There is a condition: "You can not use any sorting functions and you should iterate the array only once"

      Delete
  2. public class TwoMaxNumbers {

    public static void main(String a[]){
    int[] A = { 1, 2, 3, 5, 8, 9, 4, 6 }; // answer should be 9 and8
    int top1 = 1;
    int top2 = 0;
    for (int i = 0; i < A.length; i++) {
    if (top1 < A[i]) {
    top2 = top1;
    top1 = A[i];
    }
    }
    System.out.println(top1 + " and " + top2);
    }

    }

    ReplyDelete
    Replies
    1. Your program will fail when highest number is in 2 place.
      e.g int[] A = { 1, 10, 3, 5, 1, 9, 4, 6 }
      your program will give output 10 and 1
      But expected output is 10 and 9

      Correct program would be:
      public static void main(String a[]){
      int[] A = { 1, 10, 3, 5, 1, 9, 4, 6 }; // answer should be 10 and 9
      int top1 = 1;
      int top2 = 0;
      for (int i = 0; i < A.length; i++) {
      if (top1 < A[i]) {
      top2 = top1;
      top1 = A[i];
      }
      else if (top2 < A[i]) {
      top2 = A[i];
      }
      }
      System.out.println(top1 + " and " + top2);
      }

      Delete
  3. That was my first option at first glance at the problem, but then I realized that there are at least 2 test-cases in which this method fails:

    1. Array contains only negative values -> In this case, the if condition will never be satisfied and the block inside the if block will never be executed, hence the top1 and top2 int will remain at their default values (1 and 0)
    2. The second largest number is after the largest number. In this case, when the second largest number comes into the loop, it if block statements will not execute because the if condition will verify if the current number checked (second number) is larger than the current largest number. This will return false, so the top2 int will not change, even though is is supposed to.

    ReplyDelete
  4. class maximum
    {
    public static void main(String a[])
    {
    int arr[]={10,13,15,4,34};
    int max1=arr[0];
    int max2;
    for(i=1;i<=arr.length();i++)
    {
    if(max1<arr[i])
    {
    max1=arr[i];
    max2=max1;
    }
    }
    System.out .println(max1+" "+max2);
    }
    }

    ReplyDelete
    Replies

    1. /* Java program to find first repeating element in arr[] */

      class Main {
      public static void main(String a[]) {
      int arr[] = { 10, 13, 15, 4, 34 };
      int max1 = arr[0];
      int max2 = 0;
      for (int i = 1; i <= arr.length - 1; i++) {
      if (max1 < arr[i]) {
      max1 = arr[i];
      max2 = max1;
      }
      }
      System.out.println(max1 + " " + max2);
      }
      }



      It is giving wrong output : 34, 34

      Delete
    2. Have to use else if statement..

      public class FirstTwoTopNumber {

      static void findFirstTwoTopNumber(int[] arrayNum) {

      int max1 = arrayNum[0];
      int max2 = 0;

      for (int i = 1; i < arrayNum.length - 1; i++) {
      if (max1 < arrayNum[i]) {

      max2 = max1;
      max1 = arrayNum[i];
      } else if (max2 < arrayNum[i]) {
      max2 = arrayNum[i];
      }
      }
      System.out.println("First Top :" + max1 + "\nSecond Top : " + max2);
      }

      public static void main(String[] args) {

      int myArray[] = { 1, 10, 3, 5, 1, 9, 4, 6 };

      findFirstTwoTopNumber(myArray);

      }

      }

      Delete
  5. when I provide duplicate numbers, first and second maximum values become the same:
    Given integer array : [1, 1, 2, 2, 4, 4, 5, 5, 3]
    First maximum number is : 5
    Second maximum number is : 5

    we can modify the else if like the following:

    public static void topTwo(int[] numbers) {
    int max1 = Integer.MIN_VALUE;
    int max2 = Integer.MIN_VALUE;
    for (int number : numbers) {
    if (number > max1) {
    max2 = max1;
    max1 = number;
    } else if (number > max2 && number!=max1) {
    max2 = number;
    }
    }

    System.out.println("Given integer array : " + Arrays.toString(numbers));
    System.out.println("First maximum number is : " + max1);
    System.out.println("Second maximum number is : " + max2);
    }


    ReplyDelete
    Replies
    1. @Can, thanks for handling duplicates, good work.

      Delete
  6. public static void getTopTwoMax(int[] arr){
    int firstMax , secondMax ;
    if(arr[0]>arr[1]){
    firstMax=arr[0];
    secondMax=arr[1];
    }
    else{
    firstMax=arr[1];
    secondMax=arr[0];
    }

    for(int i=2;ifirstMax ){
    firstMax= arr[i];
    }
    if(arr[i]>secondMax&&arr[i]<firstMax){
    secondMax= arr[i];
    }
    }
    System.out.println("FirstMax="+firstMax+" SecondMax="+secondMax);

    }

    ReplyDelete
  7. public class test17 {

    public static void main(String[] args)
    {
    int[] numbers={45,23,56,23,56,4,89,4,3};
    int intTopElement=numbers[0];
    int intSecondTopElement=numbers[0];
    for(int i=0;iintTopElement)
    {
    intSecondTopElement=intTopElement;
    intTopElement=numbers[i];
    }
    }
    System.out.println("Top Element: "+ intTopElement);
    System.out.println("Second Top Element: "+intSecondTopElement);
    }

    }

    ReplyDelete
  8. class TwoMaxNumbers
    {

    public static void main(String... s)
    {
    int[] A = { 1, 2, 3, 5, 8, 9, 4, 6 };
    int top1 = 1;
    int top2 = 0;
    for (int i = 0; i < A.length; i++)
    {
    if (top1 < A[i])
    {
    top2 = top1;
    top1 = A[i];
    }
    }
    System.out.println(top1 + " and " + top2);
    }

    }

    ReplyDelete
  9. def findToptwo(numlist):
    max = numlist[0]
    max1 = numlist[1]
    for i in range(2,len(numlist)):
    if numlist[i] > max:
    max1 = max
    max = numlist[i]
    elif numlist[i]>max1:
    max1 = numlist[i]
    return max,max1

    ReplyDelete
  10. This comment has been removed by the author.

    ReplyDelete
  11. #include
    int main()
    {
    int n,arr[100],i;
    scanf("%d",&n);
    for(i=0;i=max1)
    max1=arr[i];
    }
    for(i=0;i=max2&&arr[i]<max1)
    max2=arr[i];
    }
    printf("%d %d",max1,max2);
    }

    ReplyDelete
  12. very elegant div/conq algorithm.

    both max's are either in left or right halves, or first max in left, and second max in right half

    but of course, it is not linear complexity. it is O (n lgN)

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.