Scope problem solution 30 days of code HackerRank

Input Format
You are not responsible for reading any input from stdin. The locked Solution class in your editor reads in  lines of input; the first line contains , and the second line describes the  array.
Output Format
You are not responsible for printing any output; the Solution class will print the value of the  instance variable.
Scope problem solution 30 days of code HackerRank

Problem solution in Java programming language.

/** Finds max abs difference 
*   Saves it to maximumDifference. **/
public void computeDifference(){
    // set max to its minimum possible value set by Constraints
    int max = 1; 
        
    // set min to its maximum possible value set by Constraints
    int min = 100;
    for(int element : elements){
        if(element < min){
            min = element;
        }
        if(element > max){
            max = element;
        }
    }
        
    this.maximumDifference = Math.abs(max - min);
}

Second method

class Difference{
    // instance variables
    private int[] elements;
    public int maximumDifference;
    
    public Difference(int[] elements){
        this.elements = elements;
    }

    /** Sorts the array
    *   Saves max abs difference between first and last element to maximumDifference. **/
    public void computeDifference(){
        Arrays.sort(elements);
        this.maximumDifference = Math.abs(elements[elements.length - 1] - elements[0]);
    }
}

Problem solution in the Swift programming language.

init(a : [Int]) {
        self.elements = a
        self.maximumDifference = 0
    }

    /** Sorts the array
    *   Saves max abs difference between first and last element to maximumDifference. **/
    func computeDifference() {
        self.elements = self.elements.sorted()
        self.maximumDifference = elements[elements.count - 1] - elements[0]
    }

Problem solution in Python programming language.

class Difference:
    def __init__(self, a):
        self.__elements = a
        self.maximumDifference = 0
    
    def computeDifference(self):
        x = 101
        y = 0

        for item in self.__elements:
            if item < x:
                x = item
            if item > y:
                y = item
            

    
        self.maximumDifference = y - x 
    # Add your code here

# End of Difference class

_ = input()
a = [int(e) for e in input().split(' ')]

d = Difference(a)
d.computeDifference()

print(d.maximumDifference)

Post a Comment

0 Comments