JavaScript 中元组的索引差异
问题
我们需要编写一个 JavaScript 函数,其以一个整数数组 arr 作为第一个也是唯一一个参数。
假设数组中有两个索引 i 和 j,它们满足以下条件 −
i < j,并且
arr[i] <= arr[j]
在所有此类索引元组 (i, j) 中,我们的函数应当返回 j - i,它是最大值。
例如,如果向该函数输入的是 −
const arr = [6, 0, 8, 2, 1, 5];
那么应当输出 −
const output = 4;
输出解释
在 (i, j) = (1, 5) 时获得了最大差异:arr[1] = 0 且 arr[5] = 5。
示例
代码如下所示 −
const arr = [6, 0, 8, 2, 1, 5];
const maximumDifference = (arr = []) => {
let max = 0
const stack = [0]
for (let i = 1; i < arr.length; i++) {
if (arr[i] < arr[stack[stack.length - 1]]) {
stack.push(i)
}
}
for (let i = arr.length - 1; i >= 0; i--) {
while (arr[i] >= arr[stack[stack.length - 1]]) {
max = Math.max(max, i - stack.pop())
}
}
return max;
};
console.log(maximumDifference(arr));输出
而控制台中的输出将是 −
4
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP