JavaScript 中最大的和和最小的索引差
问题
JavaScript函数,它接受整数数组arr作为第一个也是唯一的参数。
我们的函数应该选择一个索引对(i,j)使得(arr[i]+arr[j])+(i-j)在数组中的所有索引对中是最大值。然后我们的函数应该返回最大值。
例如,如果函数的输入是-
const arr = [8, 1, 5, 2, 6];
那么输出应该是-
const output = 11;
输出说明
因为如果我们选择i=0和j=2那么值将是-
(8 + 5) + (0 - 2) = 11
对于任何索引对,这确实是最大值。
示例
此代码将是-
const arr = [8, 1, 5, 2, 6]; const findMaximum = (arr = []) => { let max = arr[0] + 0; let res = -Infinity; for(let i = 1; i < arr.length; i++){ res = Math.max(res, max + arr[i] - i); max = Math.max(arr[i] + i, max); }; return res; }; console.log(findMaximum(arr));输出结果
控制台中的输出将是-
11