Find the biggest difference between any two numbers in array?
Approach:
- Assume array of integer arr = [5,9,66,8,37]
- Two calculate biggest difference between two numbers logic is largest number - smallest number.
- By arranging the array in ascending order we get the first element which is smallest and the last element which is largest.
- Now the array look like integer arr =[5,8,9,37,66]
- Here the solution is last element (largest number)- first element(smallest number) i.e; 66-5= 61
Implementing in Java
/* Read input from STDIN. Print your output to STDOUT*/
import java.io.*;
import java.util.*;
public class BiggestDifference{
public static void main(String args[] ) throws Exception {
//Takes user input
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
//create an array depending upon the number of user inputs
int[] array = new int[n];
//insert user input elements into the array
for(int i = 0; i < n; i++)
{
array[i] = sc.nextInt();
}
//sort the array in ascending order
Arrays.sort(array);
//print biggest difference between largest number and smallest number in the array
System.out.println(array[n-1] - array[0]);
}
}
Output :
61
Happy coding😊
Hi there ! Im a experienced android developer with 4 years of relevant experience Skills include Android,Core Java ,Oops and Kotlin.
Comments
Post a Comment