Maximum Difference in An Array Java

0
626

Maximum Difference in An Array Java

Maximum Difference in An Array Java
Maximum Difference in An Array Java

This is a Java programme that finds the largest difference between two elements in an array.
Enter the array’s scale, followed by all of the array’s components. Now we look at all possible differences between two elements and choose the ones with the greatest difference.

Here is the source code for the Java Program to Find 2 Elements in an Array with the Largest Difference. On a Windows machine, the Java programme was successfully compiled and executed. Below is a screenshot of the program’s production.

Programme – Maximum Difference in An Array Java

import java.util.Scanner;
public class Largest_Difference
{
public static void main(String[] args)
{
int n, x, count = 0, i = 0, temp = 0;
Scanner s = new Scanner(System.in);
System.out.print(“Enter no. of elements you want in array:”);
n = s.nextInt();
int a[] = new int[n];
System.out.println(“Enter all the elements:”);
for(i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
int diff, greatest_diff;
greatest_diff = 0;
int a1 = 0, a2 = 0;
for(i = 0; i < n; i++)
{
for(int j = i + 1; j < n; j++)
{
diff = Math.abs(a[i] – a[j]);
if(diff > greatest_diff)
{
greatest_diff = diff;
a1 = i;
a2 = j;
}
}
}
System.out.println(“Greatest Difference:”+greatest_diff);
System.out.println(“Two elements with largest difference:”+a[a1]+” and “+a[a2]);
}
}

Output – Maximum Difference in An Array Java

$ javac Largest_Difference.java $ java Largest_Difference   Enter no. of elements you want in array:7 Enter all the elements: -2 4 5 6 2 7 -3 Greatest Difference:10 Two elements with largest difference:7 and -3

Array data structure – Wikipedia

LEAVE A REPLY

Please enter your comment!
Please enter your name here