Task
Complete the Difference class by writing the following:
- A class constructor that takes an array of integers as a parameter and saves it to the __elements instance variable.
- A computeDifference method that finds the maximum absolute difference between any 2 numbers in __elements and stores it in the maximumDifference instance variable.
Input Format
You are not responsible for reading any input from stdin. The locked Solution class in the editor reads in 2 lines of input. The first line contains N, the size of the elements array. The second line has 2 space-separated integers that describe the __elements array.
Output Format
You are not responsible for printing any output; the Solution class will print the value of the maximumDifference instance variable.
Sample Input
STDIN Function
----- --------
3 __elements[] size N = 3
1 2 5 __elements = [1, 2, 5]
Sample Output
4
Solutions:
1)Java:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
class Difference {
private int[] elements;
public int maximumDifference;
Difference(int[] a){
this.elements = a;
}
public void computeDifference(){
Difference.sortArray(this.elements,this.elements.length);
this.maximumDifference = this.elements[this.elements.length-1]-this.elements[0];
}
private static void sortArray(int array[], int n)
{
for (int i = 1; i < n; i++)
{
int j = i;
int a = array[i];
while ((j > 0) && (array[j-1] > a))
{
array[j] = array[j-1];
j--;
}
array[j] = a;
}
}
}
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
sc.close();
Difference difference = new Difference(a);
difference.computeDifference();
System.out.print(difference.maximumDifference);
}
}