JavaScript 中具有最大乘法的子陣列
我們需要編寫一個 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP