Skip to content

Instantly share code, notes, and snippets.

@batogov
Created September 20, 2017 13:38
Show Gist options
  • Save batogov/6ca1a5ab2e78428423cc88395a90db57 to your computer and use it in GitHub Desktop.
Save batogov/6ca1a5ab2e78428423cc88395a90db57 to your computer and use it in GitHub Desktop.
Наибольшее произведение
var unsortedArray = [-10, 7, 29, 30, 5, -10, -70];
computeProduct(unsortedArray);
/*
Сортирующая функция. Если её не передать методу sort, то элементы
сортируются путём преобразования их в строки и сравнения строк.
*/
function sortIntegers(a, b) {
return a - b;
}
// Наибольшее произведение - это (min1 * min2 * max1 || max1 * max2 * max3)
function computeProduct(unsorted) {
var sortedArray = unsorted.sort(sortIntegers);
var firstProduct = 1, secondProduct2 = 1;
var lastElement = sortedArray.length - 1;
// Получаем произведение трёх наибольших элементов уже отсортированного массива
for (var x = lastElement; x > lastElement - 3; x--) {
firstProduct = firstProduct * sortedArray[x];
}
secondProduct = sortedArray[0] * sortedArray[1] * sortedArray[lastElement];
if (firstProduct > secondProduct) return firstProduct;
return secondProduct;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment