Find the largest difference between any two elements in an array of integers.

Given an array of integers, this function returns the largest difference between any two elements in the array.

Problem

Given an array of integers, write a function that returns the largest difference between any two elements in the array.
Example input: [2, 4, 6, 10]
Example output: 8

Solution

This solution is in JavaScript. Our A.I. can create solutions in multiple languages.
by kayakane
// Solution:
// The optimal solution is to sort the array and then subtract the first element from the last element.
// This is optimal because it is O(n log n) time complexity.

function largestDifference(arr) {
  arr.sort((a, b) => a - b);
  return arr[arr.length - 1] - arr[0];
}

console.log(largestDifference([2, 4, 6, 10]));

A.I. Evaluation of the Solution

The candidate's solution is correct and demonstrates a level of completeness. The approach is also correct.

Evaluated at: 2022-11-27 00:16:08