Search Small Ones in Java
You are given with an array, now you need to find the small and second small element from the array and then show sum of small and second small output.
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
import java.util.*; | |
public class SmallAndSecondSmall { | |
public static void main(String [] args){ | |
Scanner sc=new Scanner(System.in); | |
int size=0; | |
size=Integer.parseInt(sc.nextLine().trim()); | |
if(size>1){ | |
String arrayElements=sc.nextLine(); | |
String [] array=arrayElements.split(" "); | |
int small=Integer.parseInt(array[0]); | |
int secondSmall=Integer.parseInt(array[1]); | |
for(int i=0;i<array.length;i++){ | |
if(Integer.parseInt(array[i])<small){ | |
secondSmall=small; | |
small=Integer.parseInt(array[i]); | |
}else if(Integer.parseInt(array[i])<secondSmall){ | |
secondSmall=Integer.parseInt(array[i]); | |
} | |
} | |
System.out.println(small+secondSmall); | |
} | |
sc.close(); | |
} | |
} |
Input
4
1 0 -1 2
Output:
-1
Input:
7
1 2 3 4 5 6 7
Output:
3
4
1 0 -1 2
Output:
-1
Input:
7
1 2 3 4 5 6 7
Output:
3
Comments
Post a Comment