写一个函数找出给定数组中的最大差值
/**
* 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.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步