In this HackerRank Day 14: Scope problem solution Complete the Difference class by writing the following:

  1. A class constructor that takes an array of integers as a parameter and saves it to the __elements instance variable.
  2. A computeDifference method that finds the maximum absolute difference between any 2 numbers in __elements and stores it in the maximumDifference instance variable.

HackerRank Day 14: Scope problem solution

Problem solution in Python programming.

	# Add your code here
    def __init__(self, elements):
        self.elements = elements
    def computeDifference(self):
        self.maximumDifference = max(self.elements)-min(self.elements)

Problem solution in Java programming.

	
    Difference(int[] a) {
        this.elements = a;
    }

    void computeDifference() {
        int minElement = 10;
        int maxElement = 0;
        int elementCount = elements.length;
        for (int i = 0; i < elementCount; i++) {
            minElement = Math.min(elements[i], minElement);
            maxElement = Math.max(elements[i], maxElement);
        }
        maximumDifference = elementCount > 0 ? maxElement - minElement : 0;
    }





Problem solution in C++ programming.

	Difference(vector<int> a) {
        this->elements = a;
    }
    void computeDifference(void) {
        int i = 0, j = 0, difference = 0;
        
        this->maximumDifference = 0;
        
        for (i = 0; i < this->elements.size(); i++) {
            for (j = 0; j < this->elements.size(); j++) {
                difference = abs(this->elements[i] - this->elements[j]);
                if (difference > this->maximumDifference) {
                    this->maximumDifference = difference;
                }
            }
        }
    }