เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของจำนวนเต็ม (บวกและลบ) เป็นอาร์กิวเมนต์แรกและอาร์กิวเมนต์เดียว ฟังก์ชันควรค้นหาและส่งคืนผลิตภัณฑ์ของอาร์เรย์ย่อยในตำแหน่งสูงสุด
ตัวอย่างเช่น −
หากอาร์เรย์อินพุตเป็น −
const arr = [4, -5, 2, -3, 1, -4, 0, -3];
จากนั้นผลลัพธ์ควรเป็น −
const output = 120
เนื่องจากอาร์เรย์ย่อยที่มีผลิตภัณฑ์สูงสุดคือ [4, -5, 2, -3]
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const arr = [4, -5, 2, -3, 1, -4, 0, -3];
const maxProduct = (arr = []) => {
if (arr.length === 0){
return 0;
};
let max = arr[0],
min = arr[0],
greatest = arr[0];
for (let i = 1; i <= arr.length - 1; i++) {
let tempMax = max * arr[i];
max = Math.max(
arr[i],
Math.max(min * arr[i], max * arr[i])
);
min = Math.min(arr[i], Math.min(min * arr[i], tempMax));
greatest = Math.max(greatest, max);
}
return greatest;
};
console.log(maxProduct(arr)); ผลลัพธ์
ต่อไปนี้เป็นเอาต์พุตคอนโซล -
120