How to find Second largest element in an Array - The Coding Shala
Home >> Interview Questions >> Second Largest Element in Array
In this post, we will learn how to Find Second Largest Element in an Array and will implement its code in Java.
Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.
In this post, we will learn how to Find Second Largest Element in an Array and will implement its code in Java.
Second Largest Element in Java
Given an array. You have to find the second largest element in the array.
Approach
First, we can find the largest element in the array then the second-largest, or we can do the same steps in a single loop.
Java Program:
class A { void findMax(Integer[] arr) { if(arr.length < 2) { System.out.println("Invalid Input"); return; } Integer first = Integer.MIN_VALUE; Integer second = first; for(Integer num : arr) { if(num > first) { second = first; first = num; } else if(num > second && num != first) { second = num; } } System.out.println("First big is: " + first); if(second == Integer.MIN_VALUE) { System.out.println("There is no second big number in array"); } else { System.out.println("Second big is: "+ second); } } } public class Main { public static void main(String[] args) { Integer[] arr = {55}; new A().findMax(arr); } }
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.
Comments
Post a Comment