ปัญหา
ฟังก์ชัน JavaScript ที่รับอาร์เรย์ของจำนวนเต็ม arr เป็นอาร์กิวเมนต์เดียว
ฟังก์ชันควรเลือกคู่ดัชนี (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