เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่ใช้อาร์เรย์ของจำนวนเต็มบวกและลบในอาร์เรย์ เนื่องจากอาร์เรย์ยังมีองค์ประกอบเชิงลบ ผลรวมขององค์ประกอบที่อยู่ติดกันอาจเป็นค่าลบหรือค่าบวก
ฟังก์ชันของเราควรเลือกอาร์เรย์ขององค์ประกอบที่อยู่ติดกันจากอาร์เรย์ที่รวมกันมากที่สุด สุดท้าย ฟังก์ชันควรส่งคืนอาร์เรย์นั้น
ตัวอย่างเช่น −
หากอาร์เรย์อินพุตเป็น −
const arr = [-2, -3, 4, -1, -2, 1, 5, -3];
ผลรวมสูงสุดที่เป็นไปได้คือ 7 และอาร์เรย์ย่อยเอาต์พุตควรเป็น -
const output = [4, -1, -2, 1, 5];
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const arr = [-2, -3, 4, -1, -2, 1, 5, -3];
const maximumSubarray = (arr = []) => {
let max = -Infinity;
let currentSum = 0;
let maxStartIndex = 0;
let maxEndIndex = arr.length - 1;
let currentStartIndex = 0;
arr.forEach((currentNumber, currentIndex) => {
currentSum += currentNumber;
if (max < currentSum) {
max = currentSum;
maxStartIndex = currentStartIndex;
maxEndIndex = currentIndex;
}
if (currentSum < 0) {
currentSum = 0;
currentStartIndex = currentIndex + 1;
}
});
return arr.slice(maxStartIndex, maxEndIndex + 1);
};
console.log(maximumSubarray(arr)); ผลลัพธ์
ต่อไปนี้เป็นผลลัพธ์บนคอนโซล -
[ 4, -1, -2, 1, 5 ]