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