Find the Biggest Difference in Array using java
You are given with an array, you need find the biggest difference in array. For this you need find largest and smallest element in array and subtract them you'll get the biggest difference.
Input
7
29 79 17 8 4 9 97
Output:
93
Input
7
1 2 3 4 5 6 7
Output:
6
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 are given with an array, you need find the biggest difference in array. | |
* For this you need find largest and smallest element in array and subtract them | |
* you'll get the biggest difference. | |
*/ | |
import java.util.*; | |
public class FindBiggestDifference { | |
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 max=Integer.parseInt(array[0]); | |
int min=Integer.parseInt(array[0]); | |
for(int i=1;i<array.length;i++){ | |
if(Integer.parseInt(array[i])>max){ | |
max=Integer.parseInt(array[i]); | |
}else if(Integer.parseInt(array[i])<min){ | |
min=Integer.parseInt(array[i]); | |
} | |
} | |
System.out.println(max-min); | |
} | |
sc.close(); | |
} | |
} |
Input
7
29 79 17 8 4 9 97
Output:
93
Input
7
1 2 3 4 5 6 7
Output:
6
Comments
Post a Comment