Java program of Alternate Numbers Difference

Question:-

Write a java program to read an array of integer elements. The program should find the difference between the alternate numbers in the array and find the index position of the smallest element with largest difference. If more than one pair has the same largest difference consider the first occurrence.

Note : When taking the difference take the absolute value i.e. neglecting the sign. Example : If it is 3-10=-7, consider it as 7.

If the array size is less than 3,Display “Invalid array size”.

Sample Input1:

6

4

3

2

10

8

6

Sample Output1:

1

Explanation :

Here alternate number difference means

4-2, 3-10, 2-8, 10-6
Neglect the sign So diff is 2,7,6,4
Largest diff is 7 —–> 3-10, here the smallest number is 3 and its index is 1. Hence the output is 1.

Sample Input2:

7

7

6

2

2

3

1

8

Sample Output2:

2

Sample Input3:

-1

Sample Output3:Invalid array size

Code:-

Main.java

import java.util.Scanner;
public class Main{
    public static void main (String[] args) {
        Scanner sc = new Scanner(System.in);
        int arr_size = sc.nextInt();
        if(arr_size <= 3){
            System.out.println("Invalid array size");
            System.exit(0);
        }
        int[] arr_int = new int[arr_size];
        int big_diff = 0;
        int small_index = 0;
        for(int i = 0; i < arr_size; i++)
            arr_int[i] = sc.nextInt();
            for(int j = 0; j < arr_size - 2; j++){
                if(Math.abs(arr_int[j] - arr_int[j+2]) > big_diff){
                    big_diff = Math.abs(arr_int[j] - arr_int[j+2]);
                    if(arr_int[j] <= arr_int[j+2])
                        small_index = j;
                    else
                        small_index = j + 2;
                }
            }
        System.out.println(small_index);
    }
}

Recommended:-

  1. Array square
  2. Generate number using odd digits
  3. Alternate Number Difference
  4. Next Greatest number
  5. Mark Comparison
  6. Print the characters in descending order
  7. Vowels in a fishBowl
  8. Least offer
  9. Ascending and descending order
  10. Mail Domain
  11. Count repeating words
  12. Sentence – Convert to upper and lower
  13. Count consecutive repeating characters
  14. Zig zag Array
  15. Pass and Fail Count
  16. Search a Course
  17. Average and Grade Calculation
  18. String – Find and replace the character (first occurrence)
  19. Sort the first and second half of an array
  20. Retail Shop
  21. Palindrome
  22. Numerology
  23. InitCap
  24. Array Compatiblilty
  25. Sum of the maximum and the minimum element
  26. String Concatenation
  27. Find Average Age
  28. Login
  29.  

Leave a Comment

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

x