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