Write a java program to find Largest Difference.

Write a program to read an integer array, find the largest difference between adjacent elements and display the index of largest difference.
EXAMPLE:
input1: {2,4,5,1,9,3,8}
output1: 4 (here largest difference 9-1=8 then return index of 9 ie,4)

Input and Output Format:
Input consists of an integer n which is the number of elements followed by n integer values.
The output consists of the integer.
Refer sample output for formatting specifications.

Sample Input 1:
7
2
4
5
1
9
3
8
Sample Output 1:
4

Find Largest Difference in Java.

import java.util.Scanner;

public class Main {
  public static int getDiffArray(int[] n1) {
    int n2, n3 = 0, n4 = 0, i;
    for (i = 0; i < n1.length - 1; i++) {
      n2 = Math.abs(n1[i] - n1[i + 1]);
      if (n2 > n3) {
        n3 = n2;
        n4 = i + 1;
      }
    }
    return n4;
  }

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int a[] = new int[20];
    for (int i = 0; i < n; i++) {
      a[i] = sc.nextInt();
    }

    System.out.println(getDiffArray(a));
  }
}

Add a Comment

Your email address will not be published. Required fields are marked *

one + nineteen =