在 JavaScript 中,返回陣列中 n 個數能夠得到的儘可能最大的乘積
我們需要編寫一個 JavaScript 函式,該函式以一個數字陣列作為第一個引數,並以一個數字作為第二個引數 n。
我們的函式應計算並返回陣列中 n 個數字的可能的最大乘積。
示例
程式碼如下 −
const getHighestProduct = (arr, num) => {
let prod = 1;
const sorter = (a, b) => a - b;
arr.sort(sorter);
if (num > arr.length || num & 2 && arr[arr.length - 1] < 0) {
return;
};
if (num % 2) {
prod = arr.pop();
num--;
};
while (num) {
prod *= arr[0] * arr[1] > arr[arr.length - 2] * arr[arr.length - 1]
? arr.shift() * arr.shift() : arr.pop() * arr.pop();
num -= 2;
};
return prod;
}
console.log(getHighestProduct([1, 10, -5, 1, -100], 3));
console.log(getHighestProduct([3, 4, 5, 6, 7], 3));
console.log(getHighestProduct([3, 4, -5, -6, -7], 3));輸出
控制檯中的輸出如下 −
5000 210 168
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP