In this HackerRank Day 14 scope 30 days of code problem, we have given A class constructor that takes an array of integers as a parameter and saves it to the instance variable. A computeDifference method finds the maximum absolute difference between any numbers and stores it in the instance variable.
Problem solution in Python 2 programming.
# Add your code here def computeDifference(self): maxDiff = 0 arr = self.__elements for i in range(len(arr)): for j in range(i+1, len(arr)): if abs(arr[j] - arr[i]) > maxDiff: maxDiff = abs(arr[j] - arr[i]) self.maximumDifference = maxDiff
Problem solution in Python 3 programming.
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
Problem solution in java programming.
// Add your code here public Difference(int[] nums) { elements = nums; } public void computeDifference() { Arrays.sort(elements); maximumDifference = elements[elements.length - 1] - elements[0]; }
Problem solution in c++ programming.
// Add your code here Difference(vector<int> arr){ elements = arr; sort(elements.begin(), elements.end()); } void computeDifference(){ maximumDifference = abs(elements[elements.size()-1] - elements[0]); }
public void computeDifference() {
Arrays.sort(elements);
maximumDifference = elements[elements.length – 1] – elements[0];
}
why not looping for this???
// Write your code here
public function __construct(array $elements)
{
$this->elements = $elements;
}
public function ComputeDifference()
{
$sortedElements = sort($this->elements);
$this->maximumDifference = $sortedElements[count($this->elements)-1] – $sortedElements[0];
echo $this->maximumDifference;
}
What is the problem with this php solution?