Second to smaller and larger in java
You will be given an array and you need to find the second largest and second smallest numbers and add them.
Note: the length of the array should not be less than 2.
Input Format -
you will be taking a number as an input from stdin which tells about the length of the array. On another line, array elements should be there with single space between them.
Output Format -
you need to print the addition of second largest and second smallest elements to the stdout.
Sample Test Case:
Sample Input:-7
48 77 7 11 49 99 78
Sample Output -
89
Note: the length of the array should not be less than 2.
Input Format -
you will be taking a number as an input from stdin which tells about the length of the array. On another line, array elements should be there with single space between them.
Output Format -
you need to print the addition of second largest and second smallest elements to the stdout.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* You will be given an array and you need to find the second largest and second smallest numbers and add them. | |
*Note: the length of the array should not be less than 2. | |
*/ | |
import java.io.*; | |
import java.util.*; | |
public class CandidateCode { | |
public static void main(String args[] ) throws Exception { | |
Scanner sc=new Scanner(System.in); | |
int size; | |
size=sc.nextInt(); | |
int [] arr=new int [size]; | |
for(int i=0;i<size;i++){ | |
arr[i]=sc.nextInt(); | |
} | |
int max=arr[0],secondMax=0,min=arr[1],secondMin=0; | |
for(int j=0;j<arr.length;j++){ | |
if(arr[j]>max){ | |
secondMax=max; | |
max=arr[j]; | |
}else if(arr[j]<min){ | |
secondMin=min; | |
min=arr[j]; | |
}else if(arr[j]<secondMin){ | |
secondMin=arr[j]; | |
}else if(arr[j]>secondMax){ | |
secondMax=arr[j]; | |
} | |
} | |
System.out.println(secondMax+secondMin); | |
sc.close(); | |
} | |
} |
Sample Test Case:
Sample Input:-7
48 77 7 11 49 99 78
Sample Output -
89
Comments
Post a Comment