Java Day 14: Scope




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 N and stores it in the maximumDifference instance variable.



  1. import java.io.*;
  2. import java.util.*;
  3. import java.text.*;
  4. import java.math.*;
  5. import java.util.regex.*;
  6. class Difference {
  7. private int[] elements;
  8. public int maximumDifference;
  9. Difference(int[] elements) {
  10. this.elements = elements;
  11. }
  12. public void computeDifference() {
  13. int max = 0;
  14. for (int i = 0; i < elements.length; i++) {
  15. for (int j = 0; j < elements.length; j++) {
  16. int abs = Math.abs(elements[i] - elements[j]);
  17. if (abs > max) max = abs;
  18. }
  19. }
  20. maximumDifference = max;
  21. }
  22. // Add your code here
  23. } // End of Difference class
  24. public class Solution {
  25. public static void main(String[] args) {
  26. Scanner sc = new Scanner(System.in);
  27. int n = sc.nextInt();
  28. int[] a = new int[n];
  29. for (int i = 0; i < n; i++) {
  30. a[i] = sc.nextInt();
  31. }
  32. sc.close();
  33. Difference difference = new Difference(a);
  34. difference.computeDifference();
  35. System.out.print(difference.maximumDifference);
  36. }
  37. }
Please click on the like button if it worked

Solution not working or have any suggestions? Please send an email to [email protected]


donate a cup of tea :)


Join Our Facebook Group

Share this solution


download android app

Popular HackerRank Java Solutions








codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube