JavaScript 中最大的总和小于的差值索引
问题
JavaScript 函数可以接受一个整数数组作为第一个也是唯一的参数:
我们的函数应该选择一个索引对 (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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP