ปัญหา
เราต้องเขียนฟังก์ชัน 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