To Find 2 Elements in the Array such that Difference between them is Largest

In first procedure sort the array elemensts in either ascending order or descending order.
Suppose in ascending order a[0] is smallest and a[n-1] is largerst if n is size of the array. and a[n-1]-a[0] is largest difference.

Second way

import java.util.Scanner;
public class Largest_Difference
{
    public static void main(String[] args)
    {
        int n,ldiff=0,diff,a1=0,a2=0,i;
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        int a[] = new int[n];
        for(i=0;i<n;i++)
        {
            a[i] = sc.nextInt();
        }
       for(i=0;i<n;i++)
        {
            for(int j=i+1;j<n;j++)
            {
                diff = Math.abs(a[i] - a[j]);
                if(diff>ldiff)
                {
                    ldiff=diff;
                    a1=i;
                    a2=j;
                }
            }
        }
        System.out.println("Greatest Difference:"+ldiff);
        System.out.println("Two elements with largest difference:"+a[a1]+" and "+a[a2]);
    }
}

i/p:
5
1 5 4 9 3
o/p:
Greatest Difference:8
Two elements with largest difference:1 and 9

No comments:

Post a Comment