- Related Questions & Answers
- Return the greatest possible product of n numbers from the array in JavaScript
- Maximum Product of Three Numbers in C++
- Subarray with the greatest product in JavaScript
- Program to find largest of three numbers - JavaScript
- C# program to find the maximum of three numbers
- Python program to find the maximum of three numbers
- Find the Product of first N Prime Numbers in C++
- How to find the greatest number in a list of numbers in Python?
- Greatest Sum Divisible by Three in C++
- Java program to find maximum of three numbers
- Program to find the common ratio of three numbers in C++
- Check three consecutive numbers - JavaScript
- Program to find the product of three elements when all are unique in Python
- Find the largest palindrome number made from the product of two n digit numbers in JavaScript
- Find the primorial of numbers - JavaScript

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

We are required to write a JavaScript function that takes in an array of Numbers as the only. The function should prepare an array of three such elements from the array that yields the greatest products amongst any three elements of the array. The function should finally return the product of those three elements.

**For example −**

If the input array is −

const arr = [-10, 7, 29, 30, 5, -10, -70];

Then the output should be −

const output = 21000

because the three numbers are 30, -10, -70

We can see that the array can or will probably contain negative elements. Therefore, in such a case the maximum product will be the greater of these two −

min1 * min2 * max1 max1 * max2 * max3

Therefore, we will solve it just like this

Following is the code −

const arr = [-10, 7, 29, 30, 5, -10, -70]; const threeProduct = (arr = []) => { const sorter = (a, b) => a -b; arr.sort(sorter); let pro1 = 1, pro2 = 1; let len = arr.length - 1; for (let i = len; i > len - 3; i--) { pro1 = pro1 * arr[i]; }; pro2 = arr[0] * arr[1] * arr[len]; return Math.max(pro1, pro2); } console.log(threeProduct(arr));

Following is the output on console −

21000

Advertisements