हमें एक 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