我们需要编写一个将整数数组作为唯一参数的JavaScript函数。
基于输入的数组,该函数应基于以下条件构造一个长度相同的新数组。
输出数组的任何对应元素应该是到目前为止遇到的三个最大数字的乘积。如果对应的索引小于3(我们尚未遇到三个元素),则对应的值应为-1。并且尽管我们可以使用非唯一值来计算乘积,但是那些非唯一值应该出现在不同的索引处。
例如-
如果输入数组是-
const arr = [1, 2, 3, 4, 5, 6];
那么输出应该是-
const output = [-1, -1, 6, 24, 60, 120];
以下是代码-
const arr = [1, 2, 3, 4, 5, 6]; const maximumTripleProduct = (arr = []) => { const res = []; const max = [arr[0], arr[1], arr[2]]; res[0] = res[1] = -1; res[2] = arr[0] * arr[1] * arr[2]; for(let i = 3; i < arr.length; i++){ max.push(arr[i]); max.sort((a, b) => b - a); max.pop(); res[i] = max[0] * max[1] * max[2]; }; return res; }; console.log(maximumTripleProduct(arr));输出结果
以下是控制台输出-
[-1, -1, 6, 24, 60, 120]