This is a Java Program to Find 2 Elements in the Array such that Difference between them is Largest.
Enter size of array and then enter all the elements of that array. Now we check for all possible difference between two elements and then select the elements whose difference is largest one.
Here is the source code of the Java Program to Find 2 Elements in the Array such that Difference between them is Largest. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.
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:
$ 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
Sanfoundry Global Education & Learning Series – 1000 Java Programs.
Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.
Next Steps:
- Get Free Certificate of Merit in Java Programming
- Participate in Java Programming Certification Contest
- Become a Top Ranker in Java Programming
- Take Java Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Practice BCA MCQs
- Practice Information Technology MCQs
- Practice Programming MCQs
- Buy Programming Books
- Apply for Java Internship