寫一個函式找出給定陣列中的最大差值

王铁柱6發表於2024-11-22
/**
 * Finds the maximum difference between any two elements in an array.
 *
 * @param {number[]} arr The input array of numbers.
 * @returns {number} The maximum difference, or 0 if the array is empty or has only one element.
 */
function findMaxDifference(arr) {
  if (arr.length <= 1) {
    return 0;
  }

  let minVal = arr[0];
  let maxDiff = 0;

  for (let i = 1; i < arr.length; i++) {
    const diff = arr[i] - minVal;
    if (diff > maxDiff) {
      maxDiff = diff;
    }
    if (arr[i] < minVal) {
      minVal = arr[i];
    }
  }

  return maxDiff;
}


// Example usage:
const arr1 = [1, 2, 3, 4, 5];
const maxDiff1 = findMaxDifference(arr1);
console.log(`Max difference in arr1: ${maxDiff1}`); // Output: 4

const arr2 = [5, 4, 3, 2, 1];
const maxDiff2 = findMaxDifference(arr2);
console.log(`Max difference in arr2: ${maxDiff2}`); // Output: 0

const arr3 = [10, 2, 5, 1, 8, 20];
const maxDiff3 = findMaxDifference(arr3);
console.log(`Max difference in arr3: ${maxDiff3}`); // Output: 18

const arr4 = [];
const maxDiff4 = findMaxDifference(arr4);
console.log(`Max difference in arr4: ${maxDiff4}`); // Output: 0

const arr5 = [5];
const maxDiff5 = findMaxDifference(arr5);
console.log(`Max difference in arr5: ${maxDiff5}`); // Output: 0


This function iterates through the array, keeping track of the minimum value encountered so far. For each element, it calculates the difference between the current element and the minimum value. If this difference is greater than the current maximum difference, it updates the maximum difference. This approach ensures that we find the largest difference between any two elements in the array in linear time (O(n)). It also handles edge cases like empty arrays and arrays with only one element.

相關文章