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