Problem:
Design and implement an algorithm to find the maximum absolute difference between adjacent pairs of elements in an array of n elements.
Solution:
package array.programs;
import java.util.Scanner;
public class MaxDifferenceOfAdjacentPairs {
int[] numbers;
int n;
int maxDiff;
public static void main(String[] args) {
MaxDifferenceOfAdjacentPairs maxDifferenceOfAdjacentPairs = new MaxDifferenceOfAdjacentPairs();
maxDifferenceOfAdjacentPairs.initializeTheArray();
maxDifferenceOfAdjacentPairs.findMaxDifferenceOfAdjacentPairs();
}
public void initializeTheArray(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter n value");
n = scanner.nextInt();
numbers = new int[n];
for (int i = 0; i < numbers.length; i++) {
System.out.println("enter number");
numbers[i] = scanner.nextInt();
}
scanner.close();
}
public void findMaxDifferenceOfAdjacentPairs(){
maxDiff = 0;
int diff = 0;
for (int i = 0; i < numbers.length - 1; i++) {
diff = Math.abs(numbers[i] - numbers[i+1]);
if(diff > maxDiff){
maxDiff = diff;
}
}
System.out.println("the maximum difference is " + maxDiff);
}
}
Output:
enter n value
3
enter number
12
enter number
34
enter number
3
the maximum difference is 31
Design and implement an algorithm to find the maximum absolute difference between adjacent pairs of elements in an array of n elements.
Solution:
package array.programs;
import java.util.Scanner;
public class MaxDifferenceOfAdjacentPairs {
int[] numbers;
int n;
int maxDiff;
public static void main(String[] args) {
MaxDifferenceOfAdjacentPairs maxDifferenceOfAdjacentPairs = new MaxDifferenceOfAdjacentPairs();
maxDifferenceOfAdjacentPairs.initializeTheArray();
maxDifferenceOfAdjacentPairs.findMaxDifferenceOfAdjacentPairs();
}
public void initializeTheArray(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter n value");
n = scanner.nextInt();
numbers = new int[n];
for (int i = 0; i < numbers.length; i++) {
System.out.println("enter number");
numbers[i] = scanner.nextInt();
}
scanner.close();
}
public void findMaxDifferenceOfAdjacentPairs(){
maxDiff = 0;
int diff = 0;
for (int i = 0; i < numbers.length - 1; i++) {
diff = Math.abs(numbers[i] - numbers[i+1]);
if(diff > maxDiff){
maxDiff = diff;
}
}
System.out.println("the maximum difference is " + maxDiff);
}
}
Output:
enter n value
3
enter number
12
enter number
34
enter number
3
the maximum difference is 31
No comments:
Post a Comment