Finding Second largest number in Array - Java - TCS - Technical Interview
Finding Second largest Number in Array :
1. First we need two variable called largest and second-largest. As next step, we need to use for-each loop to get the elements one by one.
2. Then as first condition is check whether value from the array is greater than largest.
3. If it is store the largest value into second-largest and value from the array into largest.
4. If not check another condition as value from the array is greater than second-largest and not equal to largest.
5. If this condition is true, store the value from the array into second-largest, is this if the second-largest value is value of last before(that is array.length-2 location).
6. It that condition also false do nothing, continue to next iteration.
Code :
package com.dinatechy.challange;
public class FindingSecondLargestNumber {
public static void main(String[] args) {
//Finding second largest number in Array
int[] arr = {34,23,54,66,43,55}; // second largest is 65
int largest = Integer.MIN_VALUE;// minus
int secondlar = Integer.MIN_VALUE;// minus
for(int a : arr) { // 34 23
if( a > largest ) { // 34 > -1 , 23 > 34
secondlar = largest; // -1
largest = a; // 34
} else if( a > secondlar && a != largest ) {// 23 > -1 && 23 != 34
secondlar = a; // 23
}
}
System.out.println("Second largest is : "+secondlar);
}
}
Do follow our Blog site, So you will the code which you have understand and learn, finally to practice without getting annoyed by changing the screen or split the screen for writing the code from the YouTube.
Comments
Post a Comment