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:-
- Array square
- Generate number using odd digits
- Alternate Number Difference
- Next Greatest number
- Mark Comparison
- Print the characters in descending order
- Vowels in a fishBowl
- Least offer
- Ascending and descending order
- Mail Domain
- Count repeating words
- Sentence – Convert to upper and lower
- Count consecutive repeating characters
- Zig zag Array
- Pass and Fail Count
- Search a Course
- Average and Grade Calculation
- String – Find and replace the character (first occurrence)
- Sort the first and second half of an array
- Retail Shop
- Palindrome
- Numerology
- InitCap
- Array Compatiblilty
- Sum of the maximum and the minimum element
- String Concatenation
- Find Average Age
- Login